MyBatis的常用注解
MyBatis也可使用注解开发方式,这样就可以减少编写Mappper映射文件
注解 | 说明 |
---|
@Insert | 实现新增 | @Update | 实现更新 | @Delete | 实现删除 | @Select | 实现查询 | @Result | 实现结果集封装 | @Results | 可以与@Result一起使用,封装多个结果集 | @One | 实现一对一结果集封装 | @Many | 实现一对多结果集封装 |
使用XML方式
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zg.mapper.UserMapper" >
<insert id="save" parameterType="user" >
insert into user values (
</insert>
<update id="update" parameterType="user">
update user set username=
</update>
<delete id="delete" parameterType="int">
delete from user where id=
</delete>
<select id="findById" parameterType="int" resultType="user">
select * from user where id=
</select>
<select id="findAll" resultType="user">
select * from user
</select>
</mapper>
UserMapper
package com.zg.mapper;
import com.zg.domain.User;
import java.util.List;
public interface UserMapper {
public void save(User user);
public void update(User user);
public void delete(int id);
public User findById(int id);
public List<User> findAll();
}
测试
package com.zg.test;
import com.zg.domain.User;
import com.zg.mapper.UserMapper;
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 mapper;
@Before
public void before() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sessionFactory.openSession(true);
mapper = sqlSession.getMapper(UserMapper.class);
}
@Test
public void testSave(){
User user = new User();
user.setId(7);
user.setUsername("Bob");
user.setPassword("123");
mapper.save(user);
}
@Test
public void testUpdate(){
User user = new User();
user.setId(7);
user.setUsername("Alice");
user.setPassword("123");
mapper.update(user);
}
@Test
public void testDelete(){
User user = new User();
mapper.delete(7);
}
@Test
public void testFindById(){
User byId = mapper.findById(2);
System.out.println(byId);
}
@Test
public void testFindAll(){
List<User> all = mapper.findAll();
for (User user : all) {
System.out.println(user);
}
}
}
MyBatis的增删改查
当我们将UserMapper.xml文件删除后,在sqlMapConfig.xml中配置查询语句的映射文件UserMapper.xml就没有了,但是映射关系还依然在,此时在sqlMapConfig.xml中就不用加载映射文件而是加载映射关系,然后将注解写在接口中就好
UserMapper接口
package com.zg.mapper;
import com.zg.domain.User;
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;
public interface UserMapper {
@Insert("insert into user values (#{id},#{username},#{password},#{birthday})")
public void save(User user);
@Update(" update user set username=#{username},password=#{password} where id=#{id}")
public void update(User user);
@Delete("delete from user where id=#{id}")
public void delete(int id);
@Select(" select * from user where id=#{id}")
public User findById(int id);
@Select(" select * from user")
public List<User> findAll();
}
核心配置文件sqlMapConfig.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">
<!--主要配置mybatis的核心配置-->
<configuration>
<!--通过properties标签加载外部properties文件-->
<properties resource="jdbc.properties"></properties>
<!--自定义别名-->
<typeAliases>
<typeAlias type="com.zg.domain.User" alias="user"></typeAlias>
</typeAliases>
<!--配置当前数据源的环境-->
<environments default="developement">
<environment id="developement">
<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>
<!--加载映射关系-->
<mappers>
<!--指定接口所在的包-->
<package name="com.zg.mapper"/>
</mappers>
</configuration>
测试代码依然同xml开发的代码
MyBatis的注解实现复杂映射开发
实现复杂关系映射之前我们可以在映射文件中通过配置<resultMap> 来实现,我们可以使用@Results注解,@result注解,@One注解,@Many注解组合完成复杂关系的配置
注解 | 用法 |
---|
@Results | 代替的是标签<resultMap> 该注解中可以使用单个@Result注解,也可以使用@Result集合,使用格式:@Results({@Results(),@Result()})或@Results(@Result()) | @Result | 代替了<id> 标签和<result> 标签@Result 中属性介绍:[column:数据库的列名;property:需要装配的属性名;one:需要使用的@One 注解(@Result(one=@One)() );many:需要使用的@Many注解(@Result(many=@many)() )] | @One (一对一) | 代替了<assocation> 标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。@One 注解属性介绍:[select:指定用来多表查询的sqlmapper,使用格式:@Result(column=" " ,property="",one=@One(select=")) ] | @Many (多对一) | 代替了<collection> 标签,是多表查询的关键,在注解中用来指定子查询返回对象集合。使用格式:@Result(property="",column="",many=@Many(select="")) |
一对一查询
用户表和订单表的关系为,一个用户多个订单,一个订单只从属一个用户 一对一查询的需求:查询一个订单,与此同时查询出该订单所属的用户 在只查询order表的时候,也要查询user表,所以需要将所有数据全部查出进行封装SELECT *,o.id oid FROM orders o,USER u WHERE o.uid=u.id 在封装时order中有user,但是user中的数据无法封装到order中,只能进行人工封装
创建Order和User实体
创建OrderMapper接口
package com.zg.mapper;
import com.zg.domain.Order;
import com.zg.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 *,o.id oid from orders o,user u where o.uid=u.id")
@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")
})
public List<Order> findAll();
}
测试
package com.zg.test;
import com.zg.domain.Order;
import com.zg.domain.User;
import com.zg.mapper.OrderMapper;
import com.zg.mapper.UserMapper;
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 MyBatisTest1 {
private OrderMapper mapper;
@Before
public void before() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sessionFactory.openSession(true);
mapper = sqlSession.getMapper(OrderMapper.class);
}
@Test
public void test1(){
List<Order> all = mapper.findAll();
for (Order order : all) {
System.out.println(order);
}
}
}
运行结果
通过外键查询另外一张表
uid属于order的外键,所以通过uid进行查询user表中的数据,但是在UserMapper中我们已经写过了findById方法,所以这里可直接使用一对一查询注解语法通过select -->UserMapper的全限定名即可
package com.zg.mapper;
import com.zg.domain.Order;
import com.zg.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")
@Results({
@Result(column = "id",property = "id"),
@Result(column = "ordertime",property = "ordertime"),
@Result(column = "total",property = "total"),
@Result(
property = "user",//要封装的属性名称是谁
column = "uid",//根据哪个字段进行查询user表数据,即外键
javaType = User.class,//要封装的实体类型
//one = @One一对一查询注解语法
//select,属性,代表查询哪个接口(UserMapper)的方法findById()获得数据
one = @One(select = "com.zg.mapper.UserMapper.findById")
)
})
public List<Order> findAll();
}
一对多查询
用户表和订单表的关系为,一个用户有多个订单,一个当但只从属一个用户 一对多查询需求:查询一个用户,与此同时查询出该用户具有的订单
select *,o.id oid from user u,orders o where u.id=o.uid
修改User实体
编写UserMapper接口
package com.zg.mapper;
import com.zg.domain.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserMapper {
@Insert("insert into user values (#{id},#{username},#{password},#{birthday})")
public void save(User user);
@Update(" update user set username=#{username},password=#{password} where id=#{id}")
public void update(User user);
@Delete("delete from user where id=#{id}")
public void delete(int id);
@Select(" select * from user where id=#{id}")
public User findById(int id);
@Select(" select * from user")
public List<User> findAll();
@Select(" select * from user")
@Results({
//id=true表示这是一个为主键的id
@Result(id = true ,column = "id",property = "id"),
@Result(column = "username",property = "username"),
@Result(column = "password",property = "password"),
@Result(
property = "orderList",
column = "id",//取user中查询出的id当作对方查询出的uid
javaType = List.class,
many = @Many(select = "com.zg.mapper.OrderMapper.findByUid")
)
})
public List<User> findUserAndOrderAll();
}
测试代码
package com.zg.test;
import com.zg.domain.Order;
import com.zg.domain.User;
import com.zg.mapper.OrderMapper;
import com.zg.mapper.UserMapper;
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 MyBatisTest2 {
private UserMapper mapper;
@Before
public void before() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sessionFactory.openSession(true);
mapper = sqlSession.getMapper(UserMapper.class);
}
@Test
public void test1(){
List<User> userAndOrderAll = mapper.findUserAndOrderAll();
for (User user : userAndOrderAll) {
System.out.println(user);
}
}
}
测试结果
多对多查询
用户表和角色表的关系为,一个用户有多个角色,一个角色被多个用户使用 多对多查询的需求:查询用户同时查询该用户的所有角色
select * from user u,sys_user_role ur ,sys_role r where u.id=ur.userId and ur.roleId=r.id
创建Role实体,修改User实体
添加UserMapper接口
package com.zg.mapper;
import com.zg.domain.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserMapper {
@Insert("insert into user values (#{id},#{username},#{password},#{birthday})")
public void save(User user);
@Update(" update user set username=#{username},password=#{password} where id=#{id}")
public void update(User user);
@Delete("delete from user where id=#{id}")
public void delete(int id);
@Select(" select * from user where id=#{id}")
public User findById(int id);
@Select(" select * from user")
public List<User> findAll();
@Select(" select * from user")
@Results({
//id=true表示这是一个为主键的id
@Result(id = true ,column = "id",property = "id"),
@Result(column = "username",property = "username"),
@Result(column = "password",property = "password"),
@Result(
property = "orderList",
column = "id",//取user中查询出的id当作对方查询出的uid
javaType = List.class,
many = @Many(select = "com.zg.mapper.OrderMapper.findByUid")
)
})
public List<User> findUserAndOrderAll();
@Select("SELECT * FROM USER")
@Results({
@Result(id = true,column = "id",property = "id"),
@Result(column = "username",property = "username"),
@Result(column = "password",property = "password"),
@Result(
property = "roleList",
column = "id",
javaType = List.class,
many = @Many(select = "com.zg.mapper.RoleMapper.findByUid")
)
})
public List<User> findUserAndRoleAll();
}
RoleMapper接口
package com.zg.mapper;
import com.zg.domain.Role;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface RoleMapper {
@Select("SELECT * FROM sys_user_role ur,sys_role r WHERE ur.roleId=r.id AND ur.userId=#{uid}")
public List<Role> findByUid(int uid);
}
使用注解配置Mapper
RoleMapper中的查询语句:SELECT * FROM sys_user_role ur,sys_role r WHERE ur.roleId=r.id AND ur.userId=#{uid}
测试结果
|