Mybatis的註解開發
一環境搭建
1.創建新工程命名ArtifactId爲:AnnotationStudentMybatis並且在pom.xml中添加依賴
添加依賴代碼如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lut</groupId>
<artifactId>AnnotationStudentMybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
2.在src-》main-》java包下新建javaclass命名分別爲:com.lut.domain.Student和com.lut.dao.IStudentDao
①在Student.class中編寫代碼屬性和getter、setter及toString()方法
具體代碼如下:
package com.lut.domain;
import java.io.Serializable;
/**
* @author Roy
* @date 2020/6/27 16:16
*/
public class Student implements Serializable {
private Integer id;
private String stuName;
private String Major;
private String sex;
private Integer age;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", stuName='" + stuName + '\'' +
", Major='" + Major + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getMajor() {
return Major;
}
public void setMajor(String major) {
Major = major;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
3.在Resources包下新建jdbc.properties和sqlMapConfig.xml配置文件
①其中jdbc.properties中數據庫配置如下:
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=123456
②其中sqlMapConfig.xml配置文件如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.ory//DTD Config 3.0//EN"
"htpp://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--引入外部配置文件-->
<properties resource="jdbcConfig.properties"></properties>
<!--配置別名-->
<typeAliases>
<package name="com.lut.domain"></package>
</typeAliases>
<!--配置環境-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--引入指定帶有註解的dao接口所在的位置-->
<mappers>
<package name="com.lut.dao"></package>
</mappers>
</configuration>
二.使用註解寫入具體方法並測試
1.在IStudentDao.java中寫入具體代碼如下:
package com.lut.dao;
import com.lut.domain.Student;
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 java.util.List;
/**
* @author Roy
* @date 2020/6/27 16:17
*/
public interface IStudentDao {
//查詢所有
@Select("select * from student")
List<Student> findAll();
//插入數據
@Insert("insert into student (stuName,major,sex,age)values(#{stuName},#{major},#{sex},#{age})")
void saveUser(Student student);
//更新學生信息
@Update("update student set stuName=#{stuName},sex=#{sex},major=#{major},age=#{age} where id=#{id}")
void updateUser(Student student);
//根據id刪除學生
@Delete("delete from student where id=#{id}")
void deleteUser(Integer id);
//根據id查詢學生信息
@Select("select * from student where id=#{id}")
Student findById(Integer id);
//模糊查詢根據姓名
@Select("select * from student where stuName like #{stuName}")
List<Student> findByName(String stuName);
//查詢學生總數
@Select("select count(*) from student")
int findTotalUser();
}
2.在test包下java包下新建java命名爲:com.lut.StudentTest
並在其中加入測試方法的代碼如下:
package com.lut;
import com.lut.dao.IStudentDao;
import com.lut.domain.Student;
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.After;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
/**
* @author Roy
* @date 2020/6/27 16:35
*/
public class StudentTest {
private SqlSessionFactory factory;
private SqlSession session;
private IStudentDao studentDao;
private InputStream in;
@Before
public void init()throws Exception{
in=Resources.getResourceAsStream("SqlMapConfig.xml");
factory=new SqlSessionFactoryBuilder().build(in);
session=factory.openSession();
studentDao=session.getMapper(IStudentDao.class);
}
@After
public void destroy()throws Exception{
session.commit();
session.close();
in.close();
}
//測試存儲
@Test
public void testSave(){
Student student=new Student();
student.setStuName("jack");
student.setSex("M");
student.setMajor("English");
student.setAge(40);
studentDao.saveStudent(student);
}
//測試更新
@Test
public void testUpdate(){
Student student=new Student();
student.setStuName("道家");
student.setMajor("道教");
student.setSex("男");
student.setAge(1500);
student.setId(1);
studentDao.updateStudent(student);
}
//測試根據id刪除
@Test
public void testDelete(){
studentDao.deleteStudent(1);
}
//測試根據id查詢
@Test
public void testFindOne(){
Student student=studentDao.findById(3);
System.out.println(student);
}
//測試模糊查詢
@Test
public void testFindByName(){
List<Student> students =studentDao.findByName("%jack%");
for(Student student:students){
System.out.println(student);
}
}
//測試查詢用戶總數
@Test
public void testFindTotal(){
int total=studentDao.findTotalUser();
System.out.println(total);
}
}
測試全部通過正確運行。
注意其中數據庫中的student表是在mysql中database:mybatis中新建的student表其中表字段如下圖所示