Mybatis学习总结四之基于注解的单表CRUD操作

先认识一下注解概念:

定义:注解(Annotation),也叫元数据。一种代码级别的说明。它是JDK1.5及以后版本引入的一个特性,与类、接口、枚举是在同一个层次。它可以声明在包、类、字段、方法、局部变量、方法参数等的前面,用来对这些元素进行说明,注释。

作用分类:

①编写文档:通过代码里标识的元数据生成文档【生成文档doc文档】

② 代码分析:通过代码里标识的元数据对代码进行分析【使用反射】

③编译检查:通过代码里标识的元数据让编译器能够实现基本的编译检查

MyBatis提供了哪些注解呢?

1.@Insert
2.@Delete

3.@Select
4.@update

接口去编写具体的实现类代码,这个具体的实现类由MyBatis帮我们动态构建出来,我们只需要直接拿来使用即可。

通过一个案例我们来了解一下注解的简单使用

前面我们讲过:Mybatis学习总结二之基于 XML 的单表CRUD操作:https://blog.csdn.net/qq_38720976/article/details/84488353

我们对比学习

1. UserMapper接口,在此实现注解

我们不需要用接口去编写具体的实现类代码,这个具体的实现类由MyBatis帮我们动态构建出来,我们只需要直接拿来使用即可。

package com.aiit.dao;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.aiit.pojo.User;

public interface UserMapper {
	//public void getAll();
	@Select("SELECT * FROM tbl_user WHERE tbl_user.id=#{id}")
	 public User selectOne(int id);
	@Select("SELECT * FROM tbl_user")
     public List<User> selectAll(); 
	@Insert("INSERT INTO tbl_user(tbl_user.name,tbl_user.age,tbl_user.address,tbl_user.birth) \r\n" + 
			"		VALUES(#{name},#{age},#{address},#{birth})")
     public int insertOne(User user);
	@Update("update tbl_user set tbl_user.address = #{address} where id = #{id}")
     public int updateOne(User user);
	@Delete("delete from tbl_user where id = #{id}")
     public int deleteOne(int id);
}

2.定义一个用户类 User

package com.aiit.pojo;

import java.util.Date;

public class User {
  
private int id;
   private String name;
   private int age;
   private String address;
   private Date birth;
public int getId() {
	return id;
}
public void setId(int id) {
	this.id = id;
}
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
public int getAge() {
	return age;
}
public void setAge(int age) {
	this.age = age;
}
public String getAddress() {
	return address;
}
public void setAddress(String address) {
	this.address = address;
}
public Date getBirth() {
	return birth;
}
public void setBirth(Date birth) {
	this.birth = birth;
}
public User(int id, String name, int age) {
	super();
	this.id = id;
	this.name = name;
	this.age = age;
}
public User() {
	super();
}
public User(int id, String name, int age, String address, Date birth) {
	super();
	this.id = id;
	this.name = name;
	this.age = age;
	this.address = address;
	this.birth = birth;
}

   
@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + ", birth=" + birth + "]";
	}


}

3.主配置文件mybatis.xml

<?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>    
     <environments default="development">
         <environment id="development">
             <transactionManager type="JDBC"/>
             <dataSource type="POOLED">
                 <property name="driver" value="com.mysql.jdbc.Driver" />
				<!-- 数据库连接URL-->
				<property name="url" value="jdbc:mysql://localhost:3306/mysqljdbc?characterEncoding=utf-8" />
				<!-- 数据库用户名和密码 -->
				<property name="username" value="root" />
				<property name="password" value="" />
             </dataSource>    
         </environment>
     </environments>
     
     <!-- 在配置文件中 关联包下的实体类的映射文件-->
      <mappers>
         <mapper class="com.aiit.dao.UserMapper"/>
     </mappers>
</configuration>

4.单元测试类TestMyBatisDemo.java

package com.aiit.test;

import static org.junit.jupiter.api.Assertions.*;

import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import com.aiit.dao.UserMapper;
import com.aiit.pojo.User;

class JUnitTest {
	static UserMapper  userDaoProxy;
	static SqlSession session;
	@BeforeAll
	static void setUpBeforeClass() throws Exception {
		String resource="mybatis.cfg.xml";
		InputStream inputStream = JUnitTest.class.getClassLoader().getResourceAsStream(resource);
		SqlSessionFactory factory = new  SqlSessionFactoryBuilder().build(inputStream);
		session = factory.openSession();
		userDaoProxy = session.getMapper(UserMapper.class);
	}

	@AfterAll
	static void tearDownAfterClass() throws Exception {
		session.commit();
		session.close();
	}

	@BeforeEach
	void setUp() throws Exception {
	}

	@AfterEach
	void tearDown() throws Exception {
	}

	@Test
	void select() {
		//单个查询
		User user1=userDaoProxy.selectOne(1);
		System.out.println(user1);
	}
	@Test
	void selectALL() {
		//查询所有
		List<User> users = userDaoProxy.selectAll();
		for(User user : users ) {
			System.out.println(user.getId()+" , "+user.getName()+" , "+user.getAge()+" , "+user.getAddress()+" , "+user.getBirth());
		}
	}
	@Test
	void insert() {
		//插入
		String string = "2016-10-24";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			User user2 = new User("beifang", 15, "Chain",sdf.parse(string));
			int insert=  userDaoProxy.insertOne(user2);
			System.out.println("插入成功"+insert);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
	}
	@Test
	void update() {
		//修改
		User user3 = new User(16, "中国");
		int update = userDaoProxy.updateOne(user3);
		System.out.println("修改成功"+update);

	}
	@Test
	void delete() {
		//删除
		int delete= userDaoProxy.deleteOne(17);
		System.out.println("删除成功"+delete);
	}

}

猜你喜欢

转载自blog.csdn.net/qq_38720976/article/details/84593982