基于SSM之Mybatis接口实现增删改查(CRUD)功能

Posted Mr·Hu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于SSM之Mybatis接口实现增删改查(CRUD)功能相关的知识,希望对你有一定的参考价值。

Mr·Hu原创作品。转载请注明出处http://www.cnblogs.com/huxiuqian/p/7642886.html 

国庆已过,要安心的学习了。

SSM框架以前做过基本的了解,相比于ssh它更为优秀。

基于JAVA应用程序用Mybatis接口简单的实现CRUD功能

基本结构: (PS:其实这个就是用的Mapper代理,只不过名字写成的Dao,在下面的代码中可以体现出来Mapper)

       

 

1.引入jar包:

  链接: https://pan.baidu.com/s/1qYmehmk

  密码: 8tbn

 2.数据库搭建

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) NOT NULL COMMENT \'用户名称\',
  `birthday` date DEFAULT NULL COMMENT \'生日\',
  `sex` char(1) DEFAULT NULL COMMENT \'性别\',
  `address` varchar(256) DEFAULT NULL COMMENT \'地址\',
  PRIMARY KEY (`id`)
)

3.日志文件配置

 

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

4.在src下创建mybatis核心配置文件SqlMapConfig.xml

 注意修改url、username、password.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 和spring整合后 environments配置将废除-->
    <environments default="development">
        <environment id="development">
        <!-- 使用jdbc事务管理-->
            <transactionManager type="JDBC" />
        <!-- 数据库连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/huiyushixun?characterEncoding=UTF-8"/>
                <property name="username" value="root" />
                <property name="password" value="abc123." />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="User.xml"/>
    </mappers>
    
</configuration>

5.编写po类

 

package com.hpe.ssm01.po;

public class User {
    private int id;
    private String username;
    private String birthday;
    private String sex;
    private String address;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getBirthday() {
        return birthday;
    }
    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "User [用户ID=" + id + ", 用户名=" + username + ", 生日=" + birthday + ", 性别=" + sex + ", 地址="
                + address + "]\\n";
    }

}

 

6.在src下创建sql映射文件User.xml

 

  1. 由mapper标签开始,由/mapper结束,可以把它想成一个空间,是映射文件  。
  2. 属性namespace:空间名,主要在代理中使用。这个namespace是唯一的。  
  3. 这里把mapper标签和接口联系在一起了,namespace=写接口路径。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hpe.ssm01.dao.UserDao">
    <!-- 增加用户 -->
    <insert id="addUser" parameterType="com.hpe.ssm01.po.User">
        insert into user (username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{address})
    </insert>
    <!-- 删除用户 -->
    <delete id="deleteUser" parameterType="int">
        delete from user where id = #{id}
    </delete>
    <!-- 修改用户 -->
    <update id="updateUser" parameterType="com.hpe.ssm01.po.User">    
        update user set username = #{username}, birthday = #{birthday}, sex = #{sex}, address = #{address} where id = #{id}    
    </update>
    <!-- 获取所有用户信息 -->
    <select id="findUser" resultType="com.hpe.ssm01.po.User">
        select * from user
    </select>
    <!-- 根据id获取用户信息 -->
    <select id="findUserById" parameterType="int" resultType="com.hpe.ssm01.po.User">
        select * from user where id = #{id}
    </select>
    <!-- 根据username模糊查询获取用户信息 -->
    <select id="findUserByName" parameterType="String" resultType="com.hpe.ssm01.po.User">
        select * from user where username like #{key}
    </select>
</mapper>

7.使用测试类进行测试(使用Junit进行测试,可以进行CRUD操作,如果想用控制台进行操作请看8、9步骤)

SqlSession别忘关闭!

 

package com.hpe.ssm01.test;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import com.hpe.ssm01.po.User;

public class MainTest {
    @Test    // junit 的测试方法 用于单元测试
    public void findUserById() throws IOException{
        // 1. 创建SqlSessionFactory
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
        
        // 2. 由工厂创建SqlSession
        SqlSession sqlSession = factory.openSession();
        
        // 3. 根据映射调用Sql
        User user = sqlSession.selectOne("com.hpe.ssm01.dao.UserDao.findUserById", 1);
        
        // 4. 打印
        System.out.println(user);
        
        // 5. 关闭SqlSession
        sqlSession.close();
    }
}

 

 

 

8.创建Mapper接口

注意:

Mapper.xml文件中的namespace与mapper接口的类路径相同。
Mapper接口方法名和Mapper.xml中定义的每个statement的id相同。 
Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql 的parameterType的类型相同。
Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同。

 

package com.hpe.ssm01.dao;

import java.util.List;

//import org.apache.ibatis.annotations.Select;

import com.hpe.ssm01.po.User;

public interface UserDao {
    //@Select("insert into user (username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{address})")
    public void addUser(User user);
    public void deleteUser(int id);
    public void updateUser(User user);
    List<User> findUser();
    //@Select("select * from user where id = #{id}")
    public User findUserById(int id);
    List<User> findUserByName(String name);
}

9.在控制台上进行增删改查操作

package com.hpe.ssm01.view;

import java.io.InputStream;
import java.util.List;
import java.util.Scanner;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.hpe.ssm01.dao.UserDao;
import com.hpe.ssm01.po.User;

public class Main {
    static Scanner s = new Scanner(System.in);
    private static SqlSessionFactory factory;
    private static InputStream inputStream;
    static {
        try {
            inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
            factory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        while (true) {
            System.out.println("***************************************");
            System.out.println("------------基于ssm的CRUD测试------------");
            System.out.println("1.增加    2.删除    3.修改    4.查询    0.退出");
            System.out.println("***************************************");
            System.out.println("请选择功能:");
            String s1 = s.next();
            switch (s1) {
            case "1":
                System.out.println("----------------添加用户----------------");
                System.out.println("请输入用户名:");
                String username = s.next();
                System.out.println("请输入生日:(XXXX-XX-XX)");
                String birthday = s.next();
                System.out.println("请输入性别:(男/女)");
                String sex = s.next();
                System.out.println("请输入地址:");
                String address = s.next();
                User user = new User();
                user.setUsername(username);
                user.setBirthday(birthday);
                user.setSex(sex);
                user.setAddress(address);
                addUser(user);
                break;
            case "2":
                System.out.println("----------------删除用户----------------");
                System.out.println("请输入需要删除的用户ID:");
                int id = s.nextInt();
                if (findUserById(id) == null) {
                    System.out.println("用户不存在,是否查询所有用户信息?Y/N");
                    String choose = s.next();
                    if ("Y".equals(choose) || "y".equals(choose)) {
                        findUser();
                    }
                } else {
                    deleteUser(id);
                }
                break;
            case "3":
                System.out.println("----------------修改用户----------------");
                System.out.println("请输入需要修改的用户ID:");
                int id1 = s.nextInt();
                if (findUserById(id1) == null) {
                    System.out.println("用户不存在,是否查询所有用户信息?Y/N");
                    String choose = s.next();
                    if ("Y".equals(choose) || "y".equals(choose)) {
                        findUser();
                    }
                } else {
                    User user1 = findUserById(id1);
                    System.out.println("是否修改用户名?Y/N");
                    String choose1 = s.next();
                    if ("Y".equals(choose1) || "y".equals(choose1)) {
                        System.out.println("请输入用户名:");
                        String username1 = s.next();
                        user1.setUsername(username1);
                    } else {
                        user1.setUsername(user1.getUsername());
                    }
                    System.out.println("是否修改生日?Y/N");
                    String choose2 = s.next();
                    if ("Y".equals(choose2) || "y".equals(choose2)) {
                        System.out.println("请输入生日:(XXXX-XX-XX)");
                        String birthday1 = s.next();
                        user1.setBirthday(birthday1);
                    } else {
                        user1.setBirthday(user1.getBirthday());
                    }
                    System.out.println("是否修改性别?Y/N");
                    String choose3 = s.next();
                    if ("Y".equals(choose3) || "y".equals(choose3)) {
                        System.out.println("请输入性别:(男/女)");
                        String sex1 = s.next();
                        user1.setSex(sex1);
                    } else {
                        user1.setSex(user1.getSex());
                    }
                    System.out.println("是否修改地址?Y/N");
                    String choose4 = s.next();
                    if ("Y".equals(choose4) || "y".equals(choose4)) {
                        System.out.println("请输入地址:");
                        String address1 = s.next();
                        user1.setAddress(address1);
                    } else {
                        user1.setAddress(user1.getAddress());
                    }
                    updateUser(user1);
                }
                break;
            case "4":
                System.out.println("----------------查询方式----------------");
                System.out.println("1.查询所有用户信息");
                System.out.println("2.按用户ID查询");
                System.out.println("3.按用户名查询(模糊查询)");
                System.out.println("PS:按除1、2、3之外,输入任意键返回主菜单");
                System.out.println("--------------------------------------");
                System.out.println("请选择功能:");
                String s2 = s.next();
                switch (s2) {
                case "1":
                    findUser();
                    break;
                case "2":
                    System.out.println("请输入需要查询的用户ID:");
                    int id2 = s.nextInt();
                    if (findUserById(id2) == null) {
                        System.out.println("用户不存在,是否查询所有用户信息?Y/N");
                        String choose = s.next();
                        if ("Y".equals(choose) || "y".equals(choose)) {
                            findUser();
                        }
                    } else {
                        System.out.println(findUserById(id2));
                    }
                    break;
                case "3":
                    System.out.println("请输入需要查询的用户名:");
                    String name2 = s.next();
                    if (findUserByName("%" + name2 + "%") == null) {
                        System.out.println("用户不存在,是否查询所有用户信息?Y/N");
                        String choose = s.next();
                        if ("Y".equals(choose) || "y".equals(choose)) {
                            findUser();
                        }
                    } else {
                        System.out.println(findUserByName("%" + name2 + "%"));
                    }
                    break;
                default:
                    System.out.println("返回主菜单");
                }
                break;
            case "0":
                System.out.println("系统已关闭");
                System.exit(0);
            default:
                System.out.println("您输入的内容有误,请重新输入");
            }
        }
    }

    private static void addUser(User user) {
        SqlSession session = null;
        try {
            session = factory.openSession();
            UserDao userDao = session.getMapper(UserDao.class);
            userDao.addUser(user);
            session.commit();
        } finally {
            session.close();
        }
    }

    private static void deleteUser(int id) {
        SqlSession session = null;
        try {
            session = factory.openSession();
            UserDao userDao = session.getMapper(UserDao.class);
            userDao.deleteUser(id);
            session.commit();
        } finally {
            session.close();
        }
    }

    private static void updateUser(User user) {
        SqlSession session = null;
        try {
            session = factory.openSession();
            UserDao userDao = session.getMapper(UserDao.class);
            userDao.updateUser(user);
            session.commit();
        } finally {
            session.close();
        }
    }

    private static void findUser() {
        SqlSession session = null;
        try {
            session = factory.openSession();
            UserDao userDao = session.getMapper(UserDao.class);
            List<User> list = userDao.findUser();
            System.out.println(list);
            session.commit();
        } finally {
            session.close();
        }
    }

    private static User findUserById(int id) {
        SqlSession session = null;
        User user = null;
        try {
            session = factory.openSession();
            UserDao userDao = session.getMapper(UserDao.class);
            user = userDao.findUserById(id);
            session.commit();
        } finally {
            session.close();
        }
        return user;
    }

    private static List<User> findUserByName(String name) {
        SqlSession session = null;
        List<User> list = null;
        try {
            session = factory.openSession();
            UserDao userDao = session.getMapper(UserDao.class);
            list = userDao.findUserByName(name);
            session.commit();
        } finally {
            session.close();
        }
        return list;
    }
}

 Mr·Hu原创作品。转载请注明出处http://www.cnblogs.com/huxiuqian/p/7642886.html 

以上是关于基于SSM之Mybatis接口实现增删改查(CRUD)功能的主要内容,如果未能解决你的问题,请参考以下文章

ssm 框架实现增删改查CRUD操作(Spring + SpringMVC + Mybatis 实现增删改查)

基于maven+ssm的增删改查之添加员工实现

基于maven+ssm的增删改查之测试相关ssm环境是否成功

基于SSM实现的MySQL增删改查

基于maven+ssm的增删改查之批量删除

基于maven+ssm的增删改查之修改员工信息