🍁博客主页:👉 不会压弯的小飞侠
✨欢迎关注:👉点赞👍收藏⭐留言✒
✨系列专栏:👉 MyBatis详解
✨如果觉得博主的文章还不错的话,请三连支持一下博主。
🔥欢迎大佬指正,一起 学习!一起加油!
一、mybatis注解完成基本的增删改查
1.常用的注解
- 注解开发越来越流行,Mybatis也可以使用注解开发方式,这样我们就可以减少编写Mapper映射文件了
- @Insert:实现新增
- @Update:实现更新
- @Delete:实现删除
- @Select:实现查询
- @Result:实现结果集封装
- @Results:可以与@Result一起使用,封装多个结果集
- @One:实现一对一结果集封装
- @Many:实现一对多结果集封装
2.增删改查
@Insert(" insert into users values(#{id},#{username},#{password},#{birthday})")
public void save(User user);
@Update(" update users set username=#{username},password=#{password},birthday=#{birthday} where id=#{id}")
public void update(User user);
@Delete(" delete from users where id=#{id}")
public void delete(int id);
@Select(" select * from users where id=#{id}")
public User findById(int id);
@Select(" select * from users")
public List<User> findAll();
二、mybatis注解实现复杂的映射开发
@Results
- 代替的是标签该注解中可以使用单个@Result注解,也可以使用@Result集合。
- 使用格式: @Results ({@Result () ,@Result () })或@Results (@Result () )代替了标签和标签
@Resut
- Result中属性介绍:
- column:数据库的列名
- property:需要装配的属性名
- one:需要使用的@One注解(@Result (one=@one)() ) )
- many:需要使用的@Many注解(@Result (many=@many)() ) )
@One (一对一)
- 代替了标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。
- One注解属性介绍:
- select:指定用来多表查询的sqlmapper
- 使用格式:@Result(column=" ",property="".one=@One(select=""))
@ Many(多对一)
- 代替了标签,是是多表查询的关键,在注解中用来指定子查询返回对象集合。
- 使用格式:@Result(property="".column="".many=@Many(select=""))
1.一对一的注解开发
@Select("select *,o.id oid from users u,orders o where u.id=o.uid")
@Results({
@Result(column = "oid",property = "id"),
@Result(column = "ordertime",property = "ordertime"),
@Result(column = "total",property = "total"),
@Result(
property = "user", //要封装的属性名称
column = "uid", //根据那个字段去查询user表的数据
javaType = User.class, //要封装的实体类型
//select 属性代表查询接口的方法获得数据
one = @One(select = "com.jkj.dao.UserMapper.findById")
)
})
/* @Select("select *,o.id oid from users u,orders o where u.id=o.uid")
@Results({
@Result(column = "oid",property = "id"),
@Result(column = "ordertime",property = "ordertime"),
@Result(column = "total",property = "total"),
@Result(column = "uid",property = "user.id"),
@Result(column = "username",property = "user.username"),
@Result(column = "password",property = "user.password"),
@Result(column = "birthday",property = "user.birthday")
})*/
public List<Order> findAll();
2.一对多的注解开发
OrderMapper
@Select("select * from orders where uid=#{uid}")
public List<Order> findByUid(int uid);
UserMapper
@Select("select * from users")
@Results({
@Result(id=true,column = "id",property = "id"),
@Result(column = "username",property = "username"),
@Result(column = "password",property = "password"),
@Result(column = "birthday",property = "birthday"),
@Result(
property = "orderList",
column = "id",
javaType = List.class,
many = @Many(select = "com.jkj.dao.OrderMapper.findByUid")
)
})
public List<User> findUsersAndOrdersAll();
3.多对多的注解开发
RoleMapper
@Select("select * from users_roles ur,roles r where ur.rolesId=r.id and ur.usersId=#{uid}")
public List<Role> findByUid(int id);
UserMapper
@Select("select * from users")
@Results({
@Result(id=true,column = "id",property = "id"),
@Result(id=true,column = "username",property = "username"),
@Result(id=true,column = "password",property = "password"),
@Result(
property = "roleList",
column = "id",
javaType = List.class,
many = @Many(select ="com.jkj.dao.RoleMapper.findByUid")
)
})
public List<User> findUsersAndRolesAll();
三、详细代码
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>MyBatis-Test</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>
2.jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatisthree
jdbc.username=root
jdbc.password=root
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 core file-->
<configuration>
<!--通过properties标签添加properties文件-->
<properties resource="jdbc.properties"></properties>
<!--自定义别名-->
<typeAliases>
<typeAlias type="com.demo.domain.User" alias="user"></typeAlias>
<typeAlias type="com.demo.domain.Order" alias="order"></typeAlias>
<typeAlias type="com.demo.domain.Role" alias="role"></typeAlias>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<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>
<!-- 加载映射关系-->
<mappers>
<package name="com.jkj.dao"/>
</mappers>
</configuration>
4.User
package com.demo.domain;
import java.util.Date;
import java.util.List;
public class User {
private int id;
private String username;
private String password;
private Date birthday;
//描述当前用户存在那些订单
private List<Order> orderList;
//描述当前用户具有哪些角色
private List<Role> roleList;
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public List<Order> getOrderList() {
return orderList;
}
public void setOrderList(List<Order> orderList) {
this.orderList = orderList;
}
public List<Role> getRoleList() {
return roleList;
}
public void setRoleList(List<Role> roleList) {
this.roleList = roleList;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", birthday=" + birthday +
", orderList=" + orderList +
", roleList=" + roleList +
'}';
}
}
5.Order
package com.demo.domain;
import java.util.Date;
public class Order {
private int id;
private Date ordertime;
private double total;
//当前订单属于哪个用户
private User user;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getOrdertime() {
return ordertime;
}
public void setOrdertime(Date ordertime) {
this.ordertime = ordertime;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String toString() {
return "Order{" +
"id=" + id +
", ordertime=" + ordertime +
", total=" + total +
", user=" + user +
'}';
}
}
6.Role
package com.demo.domain;
public class Role {
private int id;
private String roleName;
private String roleDesc;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleDesc() {
return roleDesc;
}
public void setRoleDesc(String roleDesc) {
this.roleDesc = roleDesc;
}
@Override
public String toString() {
return "Role{" +
"id=" + id +
", roleName='" + roleName + '\'' +
", roleDesc='" + roleDesc + '\'' +
'}';
}
}
7.UserMapper
package com.jkj.dao;
import com.jkj.domain.Role;
import com.jkj.domain.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserMapper {
@Insert(" insert into users values(#{id},#{username},#{password},#{birthday})")
public void save(User user);
@Update(" update users set username=#{username},password=#{password},birthday=#{birthday} where id=#{id}")
public void update(User user);
@Delete(" delete from users where id=#{id}")
public void delete(int id);
@Select(" select * from users where id=#{id}")
public User findById(int id);
@Select(" select * from users")
public List<User> findAll();
@Select("select * from users")
@Results({
@Result(id=true,column = "id",property = "id"),
@Result(column = "username",property = "username"),
@Result(column = "password",property = "password"),
@Result(column = "birthday",property = "birthday"),
@Result(
property = "orderList",
column = "id",
javaType = List.class,
many = @Many(select = "com.jkj.dao.OrderMapper.findByUid")
)
})
public List<User> findUsersAndOrdersAll();
@Select("select * from users")
@Results({
@Result(id=true,column = "id",property = "id"),
@Result(id=true,column = "username",property = "username"),
@Result(id=true,column = "password",property = "password"),
@Result(
property = "roleList",
column = "id",
javaType = List.class,
many = @Many(select ="com.jkj.dao.RoleMapper.findByUid")
)
})
public List<User> findUsersAndRolesAll();
}
}
8.OrderMapper
package com.jkj.dao;
import com.jkj.domain.Order;
import com.jkj.domain.User;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface OrderMapper {
@Select("select * from orders where uid=#{uid}")
public List<Order> findByUid(int uid);
@Select("select *,o.id oid from users u,orders o where u.id=o.uid")
@Results({
@Result(column = "oid",property = "id"),
@Result(column = "ordertime",property = "ordertime"),
@Result(column = "total",property = "total"),
@Result(
property = "user", //要封装的属性名称
column = "uid", //根据那个字段去查询user表的数据
javaType = User.class, //要封装的实体类型
//select 属性代表查询接口的方法获得数据
one = @One(select = "com.jkj.dao.UserMapper.findById")
)
})
/* @Select("select *,o.id oid from users u,orders o where u.id=o.uid")
@Results({
@Result(column = "oid",property = "id"),
@Result(column = "ordertime",property = "ordertime"),
@Result(column = "total",property = "total"),
@Result(column = "uid",property = "user.id"),
@Result(column = "username",property = "user.username"),
@Result(column = "password",property = "user.password"),
@Result(column = "birthday",property = "user.birthday")
})*/
public List<Order> findAll();
}
9.RoleMapper
package com.jkj.dao;
import com.jkj.domain.Role;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface RoleMapper {
@Select("select * from users_roles ur,roles r where ur.rolesId=r.id and ur.usersId=#{uid}")
public List<Role> findByUid(int id);
}
10.MyBatisTest
package com.jkj.test;
import com.jkj.dao.OrderMapper;
import com.jkj.dao.UserMapper;
import com.jkj.domain.Order;
import com.jkj.domain.Role;
import com.jkj.domain.User;
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.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyBatisTest {
private UserMapper userMapper;
private OrderMapper orderMapper;
private SqlSession sqlSession;
@Before
public void before() throws IOException {
//1.加载MyBatis的核心配置文件获取sqlSessionFactory
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取sqlSession,执行sql
sqlSession = sqlSessionFactory.openSession(true);
userMapper = sqlSession.getMapper(UserMapper.class);
orderMapper = sqlSession.getMapper(OrderMapper.class);
}
@Test
public void save(){
User user=new User();
user.setUsername("jack");
user.setPassword("666");
userMapper.save(user);
sqlSession.close();
}
@Test
public void update(){
User user=new User();
user.setId(6);
user.setPassword("000");
userMapper.update(user);
sqlSession.close();
}
@Test
public void delete(){
userMapper.delete(7);
sqlSession.close();
}
@Test
public void findById(){
User user = userMapper.findById(2);
System.out.println(user);
sqlSession.close();
}
@Test
public void findAll(){
List<User> users = userMapper.findAll();
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void findOrderAll(){
List<Order> orderList = orderMapper.findAll();
for (Order orders : orderList) {
System.out.println(orders);
}
sqlSession.close();
}
@Test
public void findUsersAndOrdersAll(){
List<User> userList = userMapper.findUsersAndOrdersAll();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void findUsersAndRolesAll() {
List<User> usersAndRolesAll = userMapper.findUsersAndRolesAll();
for (User user : usersAndRolesAll) {
System.out.println(user);
}
}
}