您现在的位置是:首页 >技术教程 >MyBaits的注解开发网站首页技术教程
MyBaits的注解开发
为什么要用MyBaits注解开发?
前面介绍了MyBatis的基本用法、关联映射、动态SQL和缓存机制等知识,所有的配置都是基于XML文件完成的,但在实际开发中,大量的XML配置文件的编写是非常繁琐的,为此,MyBatis提供了更加简便的基于注解的配置方式。
基于注解的单表增删改查
代码示例:
1.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>org.example</groupId>
<artifactId>_20230503</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</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>
2.建表∶在mybatis数据库中创建名为tb_worker的数据表,同时预先插入几条测试数据。
3.根据数据库的表结构,创建实体类Worker
package cn.hdc.pojo;
public class Worker {
private int id;
private String name;
private int age;
private String sex;
private String worker_id;
@Override
public String toString() {
return "Worker{" +
"id=" + id +
", name='" + name + ''' +
", age=" + age +
", sex='" + sex + ''' +
", worker_id='" + worker_id + ''' +
'}';
}
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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getWorker_id() {
return worker_id;
}
public void setWorker_id(String worker_id) {
this.worker_id = worker_id;
}
}
4.创建WorkerMapper接口声明要实现的方法:
package cn.hdc.mapper;
import cn.hdc.pojo.Worker;
import org.apache.ibatis.annotations.*;
public interface WorkerMapper {
@Select("select * from tb_worker where id=#{id}")
public Worker findWorker(int id);
@Insert("insert into tb_worker values (null,#{name},#{age},#{sex},#{worker_id})")
public int insertWorker(Worker worker);
@Update("update tb_worker set name=#{name},age=#{age} where id=#{id}")
public int updateWorker(Worker worker);
@Delete("delete from tb_worker where id=#{id}")
public int deleteWorker(int id);
@Select("select * from tb_worker where id=#{param1} and name=#{param2}")
public Worker selectWorkerByIdAndName(@Param("param1") int id, @Param("param2") String name);
}
5.创建MyBatisUtils工具类
package cn.hdc.utils;
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 java.io.IOException;
import java.io.Reader;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory = null;
static {
try {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static SqlSession getSession() {
return sqlSessionFactory.openSession();
}
}
6.创建db.properties
driver.driver=com.mysql.cj.jdbc.Driver
driver.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
driver.username=root
driver.password=666666
7.创建mybaits-config.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>
<!-- 环境配置 -->
<!-- 加载类路径下的属性文件 -->
<properties resource="db.properties"/>
<!-- 数据库连接相关配置 ,db.properties文件中的内容-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver.driver}"/>
<property name="url" value="${driver.url}"/>
<property name="username" value="${driver.username}"/>
<property name="password" value="${driver.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="cn.hdc.mapper"/>
</mappers>
</configuration>
8.创建测试类WorkerMapperTest
package cn.hdc.mapper;
import cn.hdc.pojo.Worker;
import cn.hdc.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class WorkerMapperTest {
private WorkerMapper workerMapper;
private SqlSession session;
@Before
public void setUp() throws Exception {
session = MybatisUtils.getSession();
}
@After
public void tearDown() throws Exception {
session.commit();
session.close();
}
@Test
public void findWorker() {
workerMapper = session.getMapper(WorkerMapper.class);
Worker worker = workerMapper.findWorker(1);
System.out.println(worker);
}
@Test
public void insertWorker() {
workerMapper = session.getMapper(WorkerMapper.class);
Worker worker = new Worker();
worker.setName("赵六");
worker.setAge(23);
worker.setSex("男");
worker.setWorker_id("1004");
int i = workerMapper.insertWorker(worker);
if (i > 0) {
System.out.println("插入成功!");
} else {
System.out.println("插入失败!");
}
}
@Test
public void updateWorker() {
workerMapper = session.getMapper(WorkerMapper.class);
Worker worker = new Worker();
worker.setName("李华");
worker.setAge(30);
worker.setId(4);
int ret = workerMapper.updateWorker(worker);
if (ret > 0) {
System.out.println("修改成功!");
} else {
System.out.println("修改失败!");
}
}
@Test
public void deleteWorker() {
workerMapper = session.getMapper(WorkerMapper.class);
int ret = workerMapper.deleteWorker(4);
if (ret > 0) {
System.out.println("删除成功!");
} else {
System.out.println("删除失败!");
}
}
@Test
public void selectWorkerByIdAndName() {
workerMapper = session.getMapper(WorkerMapper.class);
Worker worker = workerMapper.selectWorkerByIdAndName(3, "王五");
System.out.println(worker);
}
}
9.项目结构:
10.@Param注解说明:
在MyBatis中,@param注解用于为SQL语句中的参数提供名称和值。它将参数名称和值映射到SQL语句中的占位符(?)或具名参数上。当使用动态SQL时,@param注解还可以帮助 MyBatis 明确哪些参数是必须提供的,哪些是可选的。使用@param注解可以提高代码可读性和维护性,并且可以避免潜在的bug。
基于注解的关联查询
—对一查询:
代码示例:
1.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>org.example</groupId>
<artifactId>_20230503</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</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>
2.建库,建表:
tb_person表:
CREATE TABLE `tb_person` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`sex` varchar(8) DEFAULT NULL,
`card_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `card_id` (`card_id`),
CONSTRAINT `tb_person_ibfk_1` FOREIGN KEY (`card_id`) REFERENCES `tb_idcard` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4
tb_idcard表:
CREATE TABLE `tb_idcard` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(18) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4
3.创建实体类:Person
package cn.hdc.pojo;
public class Person {
private int id;
private String name;
private int age;
private String sex;
private IdCard idCard;
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + ''' +
", age=" + age +
", sex='" + sex + ''' +
", idCard=" + idCard +
'}';
}
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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public IdCard getIdCard() {
return idCard;
}
public void setIdCard(IdCard idCard) {
this.idCard = idCard;
}
}
4.创建实体类:IdCard:
package cn.hdc.pojo;
public class IdCard {
private int id;
private String code;
@Override
public String toString() {
return "IdCard{" +
"id=" + id +
", code='" + code + ''' +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
5.创建接口IdCardMapper:
package cn.hdc.mapper;
import cn.hdc.pojo.IdCard;
import org.apache.ibatis.annotations.Select;
public interface IdCardMapper {
@Select("select * from tb_idCard where id = #{id}")
public IdCard selectIdCardById(int id);
}
6.创建接口PersonMapper:
package cn.hdc.mapper;
import cn.hdc.pojo.Person;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
public interface PersonMapper {
@Select("select * from tb_person where id=#{id}")
@Results(@Result(
column = "card_id",
property = "idCard",
one = @One(select = "cn.hdc.mapper.IdCardMapper.selectIdCardById")
))
public Person selectPersonById(int id);
}
7.创建MyBatisUtils工具类:
package cn.hdc.utils;
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 java.io.IOException;
import java.io.Reader;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory = null;
static {
try {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static SqlSession getSession() {
return sqlSessionFactory.openSession();
}
}
8.db.properties:
driver.driver=com.mysql.cj.jdbc.Driver
driver.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
driver.username=root
driver.password=666666
9.mybaits-config.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>
<!-- 环境配置 -->
<!-- 加载类路径下的属性文件 -->
<properties resource="db.properties"/>
<!-- 数据库连接相关配置 ,db.properties文件中的内容-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver.driver}"/>
<property name="url" value="${driver.url}"/>
<property name="username" value="${driver.username}"/>
<property name="password" value="${driver.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="cn.hdc.mapper"/>
</mappers>
</configuration>
10.创建PersonMapperTest,测试类:
package cn.hdc.mapper;
import cn.hdc.pojo.Person;
import cn.hdc.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class PersonMapperTest {
private SqlSession session;
private PersonMapper personMapper;
@Before
public void setUp() throws Exception {
session = MybatisUtils.getSession();
}
@After
public void tearDown() throws Exception {
session.commit();
session.close();
}
@Test
public void selectPersonById() {
personMapper = session.getMapper(PersonMapper.class);
Person person = personMapper.selectPersonById(1);
System.out.println(person);
}
}
11.项目结构:
12.运行结果:
一对多查询:
代码示例:
1.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>org.example</groupId>
<artifactId>_20230503</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</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>
2.db.properties
driver.driver=com.mysql.cj.jdbc.Driver
driver.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
driver.username=root
driver.password=666666
3.mybatis-config.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>
<!-- 环境配置 -->
<!-- 加载类路径下的属性文件 -->
<properties resource="db.properties"/>
<!-- 数据库连接相关配置 ,db.properties文件中的内容-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver.driver}"/>
<property name="url" value="${driver.url}"/>
<property name="username" value="${driver.username}"/>
<property name="password" value="${driver.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="cn.hdc.mapper"/>
</mappers>
</configuration>
4.MyBaitsUtils工具类:
package cn.hdc.utils;
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 java.io.IOException;
import java.io.Reader;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory = null;
static {
try {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static SqlSession getSession() {
return sqlSessionFactory.openSession();
}
}
5.建库建表:
tb_user表:
CREATE TABLE `tb_user` (
`id` int(32) NOT NULL AUTO_INCREMENT,
`username` varchar(32) DEFAULT NULL,
`address` varchar(256) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4
tb_orders表:
CREATE TABLE `tb_orders` (
`id` int(32) NOT NULL AUTO_INCREMENT,
`number` varchar(32) NOT NULL,
`user_id` int(32) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
CONSTRAINT `tb_orders_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `tb_user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4
6.创建实体类:User:
package cn.hdc.pojo;
import java.util.List;
public class User {
private int id;
private String username;
private String address;
private List<Orders> ordersList;
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + ''' +
", address='" + address + ''' +
", ordersList=" + ordersList +
'}';
}
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 getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public List<Orders> getOrdersList() {
return ordersList;
}
public void setOrdersList(List<Orders> ordersList) {
this.ordersList = ordersList;
}
}
7.创建实体类:Orders:
package cn.hdc.pojo;
public class Orders {
private int id;
private String number;
private int userId;
@Override
public String toString() {
return "Orders{" +
"id=" + id +
", number='" + number + ''' +
", userId=" + userId +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
8.创建接口OrdersMapper:
package cn.hdc.mapper;
import cn.hdc.pojo.Orders;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface OrdersMapper {
@Select("select * from tb_orders where user_id = #{uid}")
@Results({
@Result(id = true, property = "id", column = "id"),
@Result(property = "number",column = "number"),
@Result(property = "userId",column = "user_id")
})
public List<Orders> selectOrdersByUserId(int uid);
}
9.创建接口:UserMapper
package cn.hdc.mapper;
import cn.hdc.pojo.User;
import org.apache.ibatis.annotations.*;
public interface UserMapper {
@Select("select * from tb_user where id = #{id}")
@Results({
@Result(id = true,property = "id",column = "id"),
@Result(property = "username",column = "username"),
@Result(property = "address",column = "address"),
@Result(property = "ordersList",column = "id",many = @Many(select = "cn.hdc.mapper.OrdersMapper.selectOrdersByUserId"))
})
public User selectUserById(int id);
}
10.创建测试类:UserMapperTest:
package cn.hdc.mapper;
import cn.hdc.pojo.User;
import cn.hdc.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class UserMapperTest {
private SqlSession session;
private UserMapper userMapper;
@Before
public void setUp() throws Exception {
session = MybatisUtils.getSession();
}
@After
public void tearDown() throws Exception {
session.commit();
session.close();
}
@Test
public void selectUserById() {
userMapper = session.getMapper(UserMapper.class);
User user = userMapper.selectUserById(1);
System.out.println(user);
}
}
11.项目结构:
12.运行结果:
多对多查询
多对多关联使用中间表:
- 在数据库中,表与表之间的多对多关联关系通常使用一个中间表来维护
1.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>org.example</groupId>
<artifactId>_20230503</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</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>
2.建库建表:
tb_orders表:
CREATE TABLE `tb_orders` (
`id` int(32) NOT NULL AUTO_INCREMENT,
`number` varchar(32) NOT NULL,
`user_id` int(32) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
CONSTRAINT `tb_orders_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `tb_user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4
tb_product表:
CREATE TABLE `tb_product` (
`id` int(32) NOT NULL AUTO_INCREMENT,
`name` varchar(32) DEFAULT NULL,
`price` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4
tb_ordersitem表:
CREATE TABLE `tb_ordersitem` (
`id` int(32) NOT NULL AUTO_INCREMENT,
`orders_id` int(32) DEFAULT NULL,
`product_id` int(32) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `orders_id` (`orders_id`),
KEY `product_id` (`product_id`),
CONSTRAINT `tb_ordersitem_ibfk_1` FOREIGN KEY (`orders_id`) REFERENCES `tb_orders` (`id`),
CONSTRAINT `tb_ordersitem_ibfk_2` FOREIGN KEY (`product_id`) REFERENCES `tb_product` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4
3.创建实体类:Orders:
package cn.hdc.pojo;
import java.util.List;
public class Orders {
private int id;
private String number;
private int userId;
private List<Product> productList;
@Override
public String toString() {
return "Orders{" +
"id=" + id +
", number='" + number + ''' +
", userId=" + userId +
", productList=" + productList +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public List<Product> getProductList() {
return productList;
}
public void setProductList(List<Product> productList) {
this.productList = productList;
}
}
4.创建实体类:Product
package cn.hdc.pojo;
import java.util.List;
public class Product {
private int id;
private String name;
private double price;
private List<Orders> ordersList;
@Override
public String toString() {
return "Product{" +
"id=" + id +
", name='" + name + ''' +
", price=" + price +
", ordersList=" + ordersList +
'}';
}
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 double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public List<Orders> getOrdersList() {
return ordersList;
}
public void setOrdersList(List<Orders> ordersList) {
this.ordersList = ordersList;
}
}
5.创建接口OrdersMapper
package cn.hdc.mapper;
import cn.hdc.pojo.Orders;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface OrdersMapper {
// @Select("select * from tb_orders where user_id = #{uid}")
// @Results({
// @Result(id = true, property = "id", column = "id"),
// @Result(property = "number", column = "number"),
// @Result(property = "userId", column = "user_id")
// })
// public List<Orders> selectOrdersByUserId(int uid);
@Select("select * from tb_orders where id = #{id}")
@Results({
@Result(id = true, column = "id", property = "id"),
@Result(column = "number", property = "number"),
@Result(column = "id", property = "productList", many = @Many(select = "cn.hdc.mapper.ProductMapper.selectProductsByOrdersId"))
})
public Orders selectOrderById(int id);
}
6.创建接口:ProductMapper
package cn.hdc.mapper;
import cn.hdc.pojo.Product;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface ProductMapper {
@Select("select * from tb_product where id in (select product_id from tb_ordersitem where orders_id=#{orderId})")
public List<Product> selectProductsByOrdersId(int orderId);
}
7.创建工具类MybatisUtils
package cn.hdc.utils;
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 java.io.IOException;
import java.io.Reader;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory = null;
static {
try {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static SqlSession getSession() {
return sqlSessionFactory.openSession();
}
}
8.db.properties
driver.driver=com.mysql.cj.jdbc.Driver
driver.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
driver.username=root
driver.password=666666
9.mybatis-config.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>
<!-- 环境配置 -->
<!-- 加载类路径下的属性文件 -->
<properties resource="db.properties"/>
<!-- 数据库连接相关配置 ,db.properties文件中的内容-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver.driver}"/>
<property name="url" value="${driver.url}"/>
<property name="username" value="${driver.username}"/>
<property name="password" value="${driver.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="cn.hdc.mapper"/>
</mappers>
</configuration>
10.创建测试类OrdersMapperTest
package cn.hdc.mapper;
import cn.hdc.pojo.Orders;
import cn.hdc.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class OrdersMapperTest {
private SqlSession session;
private OrdersMapper ordersMapper;
@Before
public void setUp() throws Exception {
session = MybatisUtils.getSession();
}
@After
public void tearDown() throws Exception {
session.commit();
session.close();
}
@Test
public void selectOrderById() {
ordersMapper = session.getMapper(OrdersMapper.class);
Orders orders = ordersMapper.selectOrderById(1);
System.out.println(orders);
}
}
11.项目结构:
12.运行结果:
案例:基于MyBatis注解的学生管理程序
代码示例:
需求:
1.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>org.example</groupId>
<artifactId>_20230503_1</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</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>
2.db.properties
driver.driver=com.mysql.cj.jdbc.Driver
driver.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
driver.username=root
driver.password=666666
3.mybatis-config.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>
<!-- 环境配置 -->
<!-- 加载类路径下的属性文件 -->
<properties resource="db.properties"/>
<!-- 数据库连接相关配置 ,db.properties文件中的内容-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver.driver}"/>
<property name="url" value="${driver.url}"/>
<property name="username" value="${driver.username}"/>
<property name="password" value="${driver.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="cn.hdc.mapper"/>
</mappers>
</configuration>
4.MyBatisUtils工具类:
package cn.hdc.utils;
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 java.io.IOException;
import java.io.Reader;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory = null;
static {
try {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static SqlSession getSession() {
return sqlSessionFactory.openSession();
}
}
5.建库建表:
s_student表:
CREATE TABLE `s_student` (
`id` int(32) NOT NULL AUTO_INCREMENT,
`name` varchar(40) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`cid` int(32) NOT NULL,
PRIMARY KEY (`id`),
KEY `cid` (`cid`),
CONSTRAINT `s_student_ibfk_1` FOREIGN KEY (`cid`) REFERENCES `c_class` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4
c_class表:
CREATE TABLE `c_class` (
`id` int(32) NOT NULL AUTO_INCREMENT,
`classname` varchar(40) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4
6.创建接口StudentMapper:
package cn.hdc.mapper;
import cn.hdc.pojo.Student;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
public interface StudentMapper {
@Select("select * from s_student where id=#{id}")
public Student selectStudent(int id);
@Update("update s_student set name=#{name},age=#{age} where id=#{id}")
public int updateStudent(Student student);
@Select("select * from s_student where cid = #{cid}")
@Results({
@Result(id = true,column = "id",property = "id"),
@Result(column = "name",property = "name"),
@Result(column = "age",property = "age")
})
public List<Student> selectStudentsByCid(int cid);
}
7.创建ClassMapper接口:
package cn.hdc.mapper;
import cn.hdc.pojo.IClass;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
public interface ClassMapper {
@Select("select * from c_class where id=#{id}")
@Results({
@Result(id = true, column = "id", property = "id"),
@Result(column = "classname", property = "classname"),
@Result(column = "id",property = "studentList",many = @Many(select = "cn.hdc.mapper.StudentMapper.selectStudentsByCid"))
})
public IClass selectClassById(int id);
}
8.创建StudentMapperTest:
package cn.hdc.mapper;
import cn.hdc.pojo.Student;
import cn.hdc.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class StudentMapperTest {
private SqlSession session;
@Before
public void setUp() throws Exception {
session = MybatisUtils.getSession();
}
@After
public void tearDown() throws Exception {
session.commit();
session.close();
}
@Test
public void selectStudent() {
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
Student student = studentMapper.selectStudent(2);
System.out.println(student);
}
@Test
public void updateStudent() {
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
Student student = new Student();
student.setName("Tom");
student.setAge(23);
student.setId(4);
int ret = studentMapper.updateStudent(student);
if (ret > 0) {
System.out.println("添加成功!");
} else {
System.out.println("添加失败!");
}
}
}
9.创建ClassMapperTest测试类:
package cn.hdc.mapper;
import cn.hdc.pojo.IClass;
import cn.hdc.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class ClassMapperTest {
private SqlSession session;
@Before
public void setUp() throws Exception {
session = MybatisUtils.getSession();
}
@After
public void tearDown() throws Exception {
session.commit();
session.close();
}
@Test
public void selectClassById() {
ClassMapper classMapper = session.getMapper(ClassMapper.class);
IClass iClass = classMapper.selectClassById(2);
System.out.println(iClass);
}
}
10.项目结构: