Mybatis基础增删改查

mybatis 的增删改查

步骤概览

  1. 创建 maven 项目, 创建 Java 工程即可
  2. 引入依赖坐标如下
<dependencies>
	 
	<dependency>
		<groupId>org.mybatisgroupId>
		<artifactId>mybatisartifactId>
		<version>3.4.5version>
	dependency>
	
	<dependency>
		<groupId>mysqlgroupId>
		<artifactId>mysql-connector-javaartifactId>
		<version>5.1.6version>
	dependency>
	
	<dependency>
		<groupId>junitgroupId>
		<artifactId>junitartifactId>
		<version>4.10version>
	dependency>
	
	<dependency>
		<groupId>log4jgroupId>
		<artifactId>log4jartifactId>
		<version>1.2.17version>
	dependency>
dependencies>
  1. 编写实体类,属性尽量使用包装类型,代码见以下 Entity 层代码
  2. 编写 Dao 层接口,详细见以西 Dao 层代码
  3. resources 目录下,创建 mapper 文件夹,编写 TestDao.xml 配置文件,导入约束文件;详见以下 Mapper 层代码
  4. 编写 SqlMapperConfig.xml 主配置文件,详见以下 SqlMapperConfig 部分
  5. 测试,详见测试代码

代理DAO方式的CRUD

Entity层

public class Test {
	private Integer id;
	private String name;
	private String content;
	public Integer getId(){
		return id;
	}
	public void setId(Integer id){
		this.id = id;
	}
	public String getName(){
		return name;
	}
	public void setName(String name){
		this.name = name;
	}
	public String getContent(){
		return content;
	}
	public void setContent(String content){
		this.content = content;
	}
	@Override
	public String toString(){
		return "Test{id="+id+",name="+name+",content="+content+"}";
	}
}

DAO层

public interface testDao {
	/*
		查询全部
	*/
	public List<Test> findAll();
	
	/*
		根据ID查询
	*/
	public Test findById();
	
	/*
		插入
	*/
	public int insert(Test test);

	/*
		删除
	*/
	public int delete(int id);

	/*
		更新
	*/
	public int update(Test test);

	/*
		获取插入数据的ID
	*/
	public int insertGetId(Test test);

	/*
		根据name模糊查询
	*/
	public List<Test> likeByName(String name);
}

Mapper层

注意文件中 namespace 绑定文件,以及参数类型等的包名,以下内容为测试包名


DOCTYPE mapper
	PUBLIC "-//mybatis.orgg//DTD Mapper 3.0//EN"
	"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.melody.Dao.TestDao">
	<select id="findAll" resultType="com.melody.entity.Test">
		select * from test
	select>

	<select id="findById" resultType="com.melody.entity.Test" parameterType="java.lang.Integer">
		select * from test where id=#{id}
	select>

	<insert id="insert" parameterType="com.melody.entity.Test">
		insert into test(name,content) values(#{name}, #{content})
	insert>

	<delete id="delete" parameterType="java.lang.Integer">
		delete from user where id=#{id}
	delete>

	<update id="update" parameterType="com.melody.entity.Test">
		update user set name=#{name}, content=#{content}
	update>

	<insert id="insertGetId" parameterType="com.melody.entity.Test">
		<selectKey keyProperty="id" resultType="int" order="AFTER">
			SELECT LAST_INSERT_ID()
		selectKey>
		insert into test(name, content) values(#{name}, #{content})
	insert>

	<select id="likeByName" resultType="com.melody.entity.Test" parameterType="java.lang.String">
		select * from test where name like '%${values}%'
	select>
mapper>

SqlMapperConfig

编写主配置文件,在 resources 目录下创建 SqlMapperConfig.xml 的配置文件(名称任意),导入对应约束,编写主配置文件


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="mysql">
        <environment id="mysql">
            
            <transactionManager type="JDBC">transactionManager>
            
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis_demo"/>
                <property name="username" value="baizeyv"/>
                <property name="password" value="fahaxiki"/>
            dataSource>
        environment>
    environments>
    <mappers>
        <mapper resource="mapper/TestDao.xml">mapper> 
    mappers>
configuration>

测试类

public class TestTest {
	private InputStream in = null;
	private SqlSession session = null;
	private TestDao mapper = null;

	@Before
	public void init() throws IOException {
		//加载主配置文件,目的是为了构建SqlSessionFactory对象
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //创建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //通过SqlSessionFactory工厂对象创建SqlSesssion对象
        session = factory.openSession();
        //通过Session创建UserDao接口代理对象
        mapper = session.getMapper(TestDao.class);
	}

	@After
    public void destory() throws IOException {
        //释放资源
        session.close();
        in.close();
    }

    /**
     * 测试查询所有的方法
     */
    @Test
    public void findAll() throws IOException {
        List<Test> tests = mapper.findAll();
        for (Test test:tests) {
            System.out.println(test.toString());
        }
    }

    @Test
    public void findById() {
        Test test = mapper.findById(2);
        System.out.println(test.toString());
    }


    @Test
    public void insert(){
        Test test = new Test();
        test.setName("melody");
        test.setContent("test content");
        int code = mapper.insert(test);
        session.commit();  
        System.out.println(code);
    }

    @Test
    public void delete(){
        int code = mapper.delete(2);
        session.commit();
        System.out.println(code);
    }

    @Test
    public void update(){
        Test test = new Test();
        user.setId(1);
        test.setName("melody");
        test.setContent("test content");
        int code = mapper.update(test);
        session.commit();
        System.out.println(code);
    }

    @Test
    public void insertGetId(){
        Test test = new Test();
        test.setName("melody");
        test.setContent("test content");
        mapper.insertGetId(test);
        session.commit();
        System.out.println(user.getId());
    }

    @Test
    public void likeByName(){
        List<Test> tests = mapper.likeByName("me");
        for (Test test: tests) {
            System.out.println(test);
        }
    }
}

你可能感兴趣的:(Mybatis,mybatis,java,spring)