1、MyBatis注解开发前的准备
1.1、MyBatis常用注解
代码语言:javascript复制@Insert:实现新增
@Update:实现更新
@Delete:实现删除
@Select:实现查询
@Result:实现结果集封装
@Results:可以与@Result 一起使用,封装多个结果集
@ResultMap:实现引用@Results 定义的封装
@One:实现一对一结果集封装
@Many:实现一对多结果集封装
@SelectProvider: 实现动态SQL映射
@CacheNamespace:实现注解二级缓存的使用
1.2、注解开发前的准备
1.2.1、创建项目
代码语言:javascript复制GroupId:com.tyschool
ArtifactId:mb005
Version:1.0-SNAPSHOT
1.2.2、编写pom.xml配置文件
代码语言:javascript复制<?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.tyschool</groupId>
<artifactId>mb005</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
1.2.3、编写SqlMapConfig.xml配置文件
代码语言:javascript复制<?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>
<properties resource="db.properties"></properties>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
<typeAliases>
<package name="com.tyschool.mb005.javabean"/>
</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>
</configuration>
数据源文件db.properties
代码语言:javascript复制jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.1.123:3306/mybatis?serverTimezone=UTC
jdbc.username=root
jdbc.password=Root12345
2、完成单表的CRUD
2.1、需求介绍
完成学生表的CRUD
2.2、编写Students.java文件
代码语言:javascript复制import java.io.Serializable;
public class Students implements Serializable {
private int sid;
private String sname;
private String ssex;
private int sage;
private int cid;
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSsex() {
return ssex;
}
public void setSsex(String ssex) {
this.ssex = ssex;
}
public int getSage() {
return sage;
}
public void setSage(int sage) {
this.sage = sage;
}
public int getCid() {
return cid;
}
public void setCid(int cid) {
this.cid = cid;
}
@Override
public String toString() {
return "Students{"
"sid=" sid
", sname='" sname '''
", ssex='" ssex '''
", sage=" sage
", cid=" cid
'}';
}
}
2.3、编写IStudentsDao.java文件
代码语言:javascript复制import java.util.List;
import com.tianyi.javabean.Students;
public interface IStudentsDao {
List<Students> findAll();
Students findById(int sid);
int addStudents(Students students);
int updateStudents(Students students);
int deleteStudents(int sid);
int addCount();
List<Students> findByName(String name);
}
配置映射
代码语言:javascript复制<mappers>
<package name="com.tyschool.mb005.students.dao"/>
</mappers>
2.4、创建测试类MbStudentsTest.java
代码语言:javascript复制package com.tianyi.test;
import com.tianyi.dao.IStudentsDao;
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 java.io.IOException;
import java.io.InputStream;
public class MbStudentsTest {
private InputStream in;
private SqlSession session;
private IStudentsDao studentsDao;
@Before
public void init()throws IOException {
in= Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
SqlSessionFactory factory=builder.build(in);
session=factory.openSession(true);
studentsDao=session.getMapper(IStudentsDao.class);
}
@After
public void destroy() throws IOException {
//session.commit();
session.close();
in.close();
}
}
3、CRUD操作-上
3.1、查询所有学生信息
3.1.1、修改findAll()方法
代码语言:javascript复制@Select("select * from students")
@Results(id="studentsMap",value={
@Result(id=true,column = "sid",property = "sid"),
@Result(column = "sname",property = "sname"),
@Result(column = "ssex",property = "ssex"),
@Result(column = "sage",property = "sage")
})
List<Students> findAll();
3.3.2、编写测试方法
代码语言:javascript复制@Test
public void findAll(){
List<Students> list=studentsDao.findAll();
for (Students s:list) {
System.out.println(s);
}
}
3.2、根据ID查询学生信息
3.2.1、修改findByID()方法
代码语言:javascript复制@Select("select * from students where sid=#{sid}")
@ResultMap("studentsMap")
Students findById(int sid);
3.2.2、编写测试方法
代码语言:javascript复制@Test
public void findById(){
Students s=studentsDao.findById(3);
System.out.println(s);
}
3.3、增加学生的记录
3.3.1、修改addStudents()方法
代码语言:javascript复制@Insert("insert into students(sname,ssex,sage)values(#{sname},#{ssex},#{sage})")
@SelectKey(keyColumn = "sid",keyProperty="sid",resultType = Integer.class,before = false,statement = {"select last_insert_id()"})
int addStudents(Students students);
3.3.2、编写测试方法
代码语言:javascript复制@Test
public void addStudents(){
Students s=new Students();
s.setSname("张九");
s.setSsex("男");
s.setSage(19);
studentsDao.addStudents(s);
}
4、CRUD操作-下
4.1、修改学生的信息
4.1.1、修改updateStudents()方法
代码语言:javascript复制@Update("update students set sname=#{sname},ssex=#{ssex},sage=#{sage} where sid=#{sid}")
int updateStudents(Students students);
4.1.2、编写测试方法
代码语言:javascript复制@Test
public void updateStudents(){
Students s=studentsDao.findById(2);
s.setSname("李好");
studentsDao.updateStudents(s);
}
4.2、删除指定ID的学生信息
4.2.1、修改deleteStudents()方法
代码语言:javascript复制@Delete("delete from students where sid=#{sid}")
int deleteStudents(int sid);
4.2.2、编写测试方法
代码语言:javascript复制@Test
public void deleteStudents(){
studentsDao.deleteStudents(9);
}
5、统计与模糊查询
5.1、查询学生表中所有记录
5.1.1、修改addCount()方法
代码语言:javascript复制@Select("select count(*) from students")
int addCount();
5.1.2、编写测试方法
代码语言:javascript复制@Test
public void addCount(){
int n=studentsDao.addCount();
System.out.println(n);
}
5.2、通过学生姓名模糊查询学生信息
5.2.1、修改findByName()方法
代码语言:javascript复制@Select("select * from students where sname like #{sname}")
List<Students> findByName(String sname);
5.2.2、编写测试方法
代码语言:javascript复制@Test
public void findByName(){
List<Students> list =studentsDao.findByName("李%");
for(Students s:list){
System.out.println(s);
}
}