原始jdbbc开发存在的问题如下:
应对上诉问题给出的解决方案:
代码实现:
1、添加MyBatis的坐标
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.13version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.12version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.26version>
dependency>
2、创建user数据库表
3、编写user实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
// 编码
private int id;
// 名字
private String username;
// 密码
private String password;
// 手机号
private String phoneNum;
}
4、编写映射文件UserMapper.xml
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="userMapper">
<select id="findAll" resultType="com.dc.entity.User">
select * from sys_user
select>
mapper>
5、编写核心文件sqlMapConfig.xml
DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/dc/mapper/UserMapper.xml"/>
mappers>
configuration>
6、编写测试类
public class SqlTest {
@Test
public void sqlTest() throws IOException {
// 加载核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
// 获取sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// 获取sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 执行sql语句
List<User> users = sqlSession.selectList("userMapper.findAll");
// 打印结果
System.out.println(users);
// 释放资源
sqlSession.close();
}
}
<insert id="save" parameterType="com.dc.entity.User">
insert into sys_user(username, email, password, phonenum) value (#{username},#{email},#{password},#{phoneNum})
insert>
@Test
public void sqlTest1() throws IOException {
// 模拟user对象
User user = new User("lisi", "[email protected]", "123", "324234324324");
// 加载核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
// 获取sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// 获取sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 执行sql语句
int insert = sqlSession.insert("userMapper.save", user);
// Mybatis执行提交事务
sqlSession.commit();
System.out.println(insert);
// 释放资源
sqlSession.close();
}
<update id="up" parameterType="com.dc.entity.User">
update sys_user set username=#{username}, password=#{password} where id = #{id}
update>
@Test
public void sqlTest2() throws IOException {
// 模拟user对象
User user = new User();
user.setId(3);
user.setUsername("wang");
user.setPassword("ersrsr");
// 加载核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
// 获取sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// 获取sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 执行sql语句
sqlSession.update("userMapper.up", user);
// Mybatis执行提交事务
sqlSession.commit();
// 释放资源
sqlSession.close();
}
<delete id="delete" parameterType="com.dc.entity.User">
delete from sys_user where id = #{id}
delete>
@Test
public void sqlTest3() throws IOException {
// 加载核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
// 获取sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// 获取sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 执行sql语句
sqlSession.update("userMapper.delete", 11);
// Mybatis执行提交事务
sqlSession.commit();
// 释放资源
sqlSession.close();
}
数据库环境的配置,支持多环境配置
其中,事务管理器(transactionManager)类型有两种:
其中,数据源(dataSource)类型有三种:
该标签的作用是加载映射的,加载方式有如下几种:
实际开发中,习惯将数据的配置信息单独抽取成一个properties文件,该标签可以加载额外配置的properties文件
类型别名是为java类型设置一个短的名字,原来的类型名称配置如下:
mybatis框架已经设置好的一些常用的类型的别名
别名 | 数据类型 |
---|---|
string | String |
long | Long |
int | Integer |
double | Double |
boolean | Boolean |
…… | …… |
常用配置
常用API:SqlSessionFactory bulid(InputStream inputSream)
通过加载mybatis的核心文件的输入流的形式构建一个SqlSessionFactory对象
String resource = "org/mybatis/bulider/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactoryBulider builder = new SqlSessionFactoryBulider();
SqlSessionFactory factory = builder.build(inputStream);
其中,Resources工具类,这个类在org.apache.ibatis.io包中。Resources类帮助你从类路径下、文件系统或一个web URL中加载资源文件
SqlSessionFactory有多个方法创建SqlSession实例。常用的有如下两个:
方法 | 解释 |
---|---|
openSession() | 会默认开启一个事务,但事务不会自动提交,也就意味着需要手动提交该事务,更新操作数据才会持久化到数据库 |
openSession(boolean autoCommit) | 参数为是否自动提交,如果设置为true,那么不需要手动提交事务 |
SqlSession实例在MyBatis中是非常强大的一个类。在这里你会看到所有执行语句、提交或回滚事务和获取映射器实例的方法。执行语句的方法主要有:
<T> T selectOne(String statement, Object parameter)
<E> List<E> selectList<String statement, Object parameter)
int insert(String statement, Object parameter)
int update(String statement, Object parameter)
int delete(String statement, Object parameter)
操作事务的主要方法有:
void commit()
void rollback()
public interface UserDao{
List<User> findAll() throws IOException;
}
public class UserDaoImpl implements UserDao{
public List<User> findAll() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactory.openSession();
List<User> userList = sqlSession.selectList("userMapper.findAll");
sqlSession.close();
return userList;
}
}
@Test
public void testTradItionDao() throws IOException {
UserDao userDao = new UserDaoImpl();
List<User> all = userDao.findAll();
System.out.println(all);
}
采用Mybatis的代理开发方式实现Dao层的开发,这种方式是企业的主流
Mapper接口开发方法只需要程序员编写Mapper接口(相当于Dao接口),由MyBatis框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao层接口实现类方法
Mapper接口开发需要遵循以下规范:
public class UserService {
public static void main(String[] args) throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User id = mapper.findById(1);
System.out.println(id);
}
}
有时候业务逻辑复杂时,在MyBatis的映射文件中,sql是动态变化的,此时之前的sql就不能满足需求了
根据实体类的不同取值,使用不同的SQL语句来进行查询。比如在id如果不为空时可以根据id查询,如果username不为空时还要加入用户名作为条件。这种情况在多条件组合查询中经常会遇到
<select id="findCondition" parameterType="com.dc.entity.User" resultType="com.dc.entity.User">
select * from sys_user
<where>
<if test="id != null">
id = #{id}
if>
<if test="username != null">
and username = #{username}
if>
where>
select>
当查询条件id和username都存在时,控制台打印的sql语句如下:
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setUsername("lucy");
user.setId(1);
User condition = mapper.findCondition(user);
System.out.println(condition);
当查询条件只有id存在时,控制台打印的sql语句如下:
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setId(1);
User condition = mapper.findCondition(user);
System.out.println(condition);
循环执行sql的拼接操作,例如:select * from user where id in(1,2,3).
<select id="findByIds" parameterType="list" resultType="com.dc.entity.User">
select * from sys_user
<where>
<foreach collection="array" open="id in (" item="id" close=")" separator=",">
#{id}
foreach>
where>
select>
测试代码片段如下:
@Test
public void sqlTest5() throws IOException {
// 加载核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
// 获取sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// 获取sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 执行sql语句
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int[] ids = {1, 2, 4};
List<User> byIds = mapper.findByIds(ids);
System.out.println(byIds);
}
sql可将重复的sql提取出来,使用时用include引用即可,最终达到sql重用的目的
无论是MyBatis在预处理语句(Preparedstatement)中设置一个参数时,还是从结果集中取出一个值时,都会用类型处理器将获取的值以合适的方式转换成java类型,下表描述了一些默认的类型处理器:
你可以重写类型处理器或创建自己的类型处理器来处理不支持的或非标准的类型。具体做法为:实现org.apache.ibatis.type.TypeHandler接口。或继承一个很便利的类 org.apache.ibatis.type.BaseTypeHandler,然后可以选择性的将它映射到一个jdbc类型。如:一个java中的Date数据类型,想将之存到数据库的时候存成一个1970年至今的毫秒值,取出来时转换成java的Date,即java的Date与数据库的varchar毫秒值之间转换
开发步骤:
代码展示:
public class DateTypeHandler extends BaseTypeHandler<Date> {
// 将Java类型转换为数据库需要的类型
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Date date, JdbcType jdbcType) throws SQLException {
long time = date.getTime();
ps.setLong(i, time);
}
// 将数据库类型转换为java类型
// String参数 要转换的数据名称
// ResultSet:查询出的结果集
@Override
public Date getNullableResult(ResultSet rs, String columnName) throws SQLException {
// 获得结果集中需要的数据(long)转换成Date类型返回
Long along = rs.getLong(columnName);
Date date = new Date(along);
return date;
}
// 将数据库类型转换为java类型
@Override
public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
Long along = rs.getLong(columnIndex);
Date date = new Date(along);
return date;
}
// 将数据库类型转换为java类型
@Override
public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
Long along = cs.getLong(columnIndex);
Date date = new Date(along);
return date;
}
}
注册:
<typeHandlers>
<typeHandler handler="com.dc.handler.DateTypeHandler">typeHandler>
typeHandlers>
测试
@Test
public void sqlTest6() throws IOException {
// 加载核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
// 获取sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// 获取sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 执行sql语句
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setUsername("cashi");
user.setPassword("sbf");
user.setBirthday(new Date(System.currentTimeMillis()));
mapper.save(user);
sqlSession.commit();
sqlSession.close();
}
MyBatis可以使用第三方的插件来对功能进行扩展,分页助手pageHelper是将分页的复杂操作进行封装,使用简单的方式即可获得分页的相关数据
开发步骤:
代码展示:
1、导入通用PageHelper坐标
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelperartifactId>
<version>5.3.0version>
dependency>
<dependency>
<groupId>com.github.jsqlparsergroupId>
<artifactId>jsqlparserartifactId>
<version>4.2version>
dependency>
2、在mybatis核心配置文件中配置PageHelper插件
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
plugin>
plugins>
3、测试分页代码实现
@Test
public void sqlTest8() throws IOException {
// 加载核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
// 获取sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// 获取sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 执行sql语句
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// 设置分页参数
List<User> userList = mapper.findAll();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
获得分页相关的其他参数
// 获得与分页相关参数
PageInfo<User> pageInfo = new PageInfo<>(userList);
System.out.println("总条数" + pageInfo.getTotal());
System.out.println("总页数" + pageInfo.getPages());
System.out.println("当前页" + pageInfo.getPageNum());
System.out.println("每页显示长度" + pageInfo.getPageSize());
System.out.println("是否第一页" + pageInfo.isIsFirstPage());
System.out.println("是否是最后一页" + pageInfo.isIsLastPage());
用户表和订单表的关系为:一个用户有多个订单,一个订单只从属于一个用户。
一对一查询的需求:查询一个订单,与此同时查询出该订单所属的用户
对应的sql语句:select * from order
o, user u where u.id = o.uid;
查询结果如下:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Order {
private int id;
private Date ordertime;
private double total;
private User user;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String username;
private String password;
private String birthday;
}
public interface OrderMapper {
List<Order> findAll();
}
<mapper namespace="com.dc.mapper.OrderMapper">
<resultMap id="orderMap" type="com.dc.entity.Order">
<result column="uid" property="user.id">result>
<result column="username" property="user.username">result>
<result column="password" property="user.password">result>
<result column="birthday" property="user.birthday">result>
resultMap>
<select id="findAll" resultMap="orderMap">
select * from user u, `order` r where r.uid = u.id
select>
测试
public class SqlTest {
@Test
public void SqlTest() throws IOException {
// 加载核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
// 获取sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// 获取sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 执行sql语句
OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
List<Order> all = mapper.findAll();
for (Order oder : all) {
// 打印结果
System.out.println(oder);
}
// 释放资源
sqlSession.close();
}
}
用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户
一对多查询的需求:查询一个用户,与此同时查询出该用户具有的订单
对应的sql语句为:
select *,o.id oid from user u left join `order` o on u.id=o.uid;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String username;
private String password;
private String birthday;
// 代表当前用户具备哪些订单
private List<Order> orderList;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Order {
private int id;
private Date ordertime;
private double total;
private User user;
}
public interface OrderMapper {
List<User> find();
}
<resultMap id="userMap" type="com.dc.entity.User">
<result column="id" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<result column="birthday" property="birthday"/>
<collection property="orderList" ofType="com.dc.entity.Order">
<result column="oid" property="id"/>
<result column="ordertime" property="ordertime"/>
<result column="total" property="total"/>
collection>
resultMap>
<select id="find" resultMap="userMap">
select *,o.id oid from user u left join `order` o on u.id=o.uid;
select>
@Test
public void SqlTest() throws IOException {
// 加载核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
// 获取sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// 获取sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 执行sql语句
OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
List<User> all = mapper.find();
for (User oder : all) {
// 打印结果
System.out.println(oder);
}
// 释放资源
sqlSession.close();
}
}
用户表和角色表的关系为:一个用户有多个角色,一个角色被多个用户使用
多对多查询的需求:查询用户同时查询出该用户的所有角色
对应的sql语句:
select u.*,r.*,r.id,u.id from sys_user u left join sys_user_role ur on u.id=ur.userId inner join sys_role r on ur.roleId=r.id;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Role {
private int id;
private String roleName;
private String roleDesc;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String username;
private String email;
private String password;
private String phoneNum;
// 代表当前用户具备哪些角色
private List<Role> orderList;
}
public interface UserMapper {
public List<User> findAllUserAndRole();
}
<mapper namespace="com.dc.mapper.UserMapper">
<resultMap id="userRoleMap" type="com.dc.model.User">
<result column="id" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<result column="email" property="email"/>
<result column="phoneNum" property="phoneNum"/>
<collection property="orderList" ofType="com.dc.model.Role">
<result column="rid" property="id"/>
<result column="rolename" property="roleName"/>
<result column="roleDesc" property="roleDesc"/>
collection>
resultMap>
<select id="findAllUserAndRole" resultMap="userRoleMap">
select u.*,r.*,r.id,u.id from sys_user u left join sys_user_role ur on u.id=ur.userId inner join sys_role r on ur.roleId=r.id;
select>
@Test
public void sqlTest() throws IOException {
// 加载核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlConfig.xml");
// 获取sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// 获取sqlsession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 执行sql语句
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> allUserAndRole = mapper.findAllUserAndRole();
for (User user : allUserAndRole) {
System.out.println(user.getUsername());
List<Role> roleList = user.getOrderList();
for (Role o : roleList) {
System.out.println(o);
}
}
}
基本的CRUD操作
public class SqlTest {
private UserMapper userMapper;
@Before
public void before() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
userMapper = sqlSession.getMapper(UserMapper.class);
}
@Test
public void testSave() {
User user = new User();
user.setUsername("zghang");
List<User> allUserAndRole = userMapper.findAllUserAndRole();
System.out.println(allUserAndRole);
}
}
@Test
public void testAdd() {
User user = new User();
user.setUsername("测试数据");
user.setPassword("123");
user.setBirthday(new Date());
userMapper.add(user);
}
@Test
public void testUpdate() throws IOException {
User user = new User();
user.setId(16);
user.setUsername("测试数据修改");
user.setPassword("abc");
user.setBirthday(new Date());
userMapper.update(user);
}
@Test
public void testDelete() throws IOException {
userMapper.delete(16);
}
@Test
public void testFindById() throws IOException {
User user = userMapper.findById(1);
System.out.println(user);
}
@Test
public void testFindAll() throws IOException {
List<User> all = userMapper.findAll();
for(User user : all){
System.out.println(user);
}
}
修改MyBaits的核心配置文件,使用了注解替代的映射文件,所以只需要加载使用了注解的mapper接口即可
<mappers>
<mapper class="com.dc.mapper.UserMapper">mapper>
mappers>
或者指定扫描包含映射关系的接口所在的包
<mappers>
<package name="com.dc.mapper">package>
mappers>
实现复杂映射之前可以在映射文件中通过配置
注解 | 说明 |
---|---|
@Resullts | 代替的是标签 |
@Result | 代替了 @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=“”)) |
查询sql语句
select * from orders;
select * from user where id=查询出订单的uid;
创建Order和User实体
public class Order {
private int id;
private Date ordertime;
private double total;
//代表当前订单从属于哪一个客户
private User user;
}
public class User {
private int id;
private String username;
private String password;
private Date birthday;
}
使用注解配置Mapper
public interface OrderMapper {
@Select("select * from orders")
@Results({
@Result(id=true,property = "id",column = "id"),
@Result(property = "ordertime",column = "ordertime"),
@Result(property = "total",column = "total"),
@Result(property = "user",column = "uid",
javaType = User.class,
one = @One(select ="com.dc.mapper.UserMapper.findById"))
})
List<Order> findAll();
}
public interface UserMapper {
@Select("select * from user where id=#{id}")
User findById(int id);
}
测试结果
private UserMapper userMapper;
@Before
public void test1() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
userMapper = sqlSession.getMapper(UserMapper.class);
}
@Test
public void testSelectOrderAndUser() {
List<Order> all = orderMapper.findAll();
for(Order order : all){
System.out.println(order);
}
}
用户表和订单表的关系为:一个用户有多个订单,一个订单只从属于一个用户
一对多查询的需求:查询一个用户,与此同时查询出该用户具有的订单
查询的sql语句:
select * from user;
select * from orders where uid=查询出用户的id;
修改User实体
public class Order {
private int id;
private Date ordertime;
private double total;
//代表当前订单从属于哪一个客户
private User user;
}
public class User {
private int id;
private String username;
private String password;
private Date birthday;
//代表当前用户具备哪些订单
private List<Order> orderList;
}
使用注解配置Mapper
public interface UserMapper {
@Select("select * from user")
@Results({
@Result(id = true,property = "id",column = "id"),
@Result(property = "username",column = "username"),
@Result(property = "password",column = "password"),
@Result(property = "birthday",column = "birthday"),
@Result(property = "orderList",column = "id",
javaType = List.class,
many = @Many(select = "com.dc.mapper.OrderMapper.findByUid"))
})
List<User> findAllUserAndOrder();
}
public interface OrderMapper {
@Select("select * from orders where uid=#{uid}")
List<Order> findByUid(int uid);
}
测试结果
List<User> all = userMapper.findAllUserAndOrder();
for(User user : all){
System.out.println(user.getUsername());
List<Order> orderList = user.getOrderList();
for(Order order : orderList){
System.out.println(order);
}
System.out.println("-----------------------------");
}
查询的sql语句
select * from user;
select * from role r,user_role ur where r.id=ur.role_id and ur.user_id=用户的id
创建Role实体,修改User实体
public class User {
private int id;
private String username;
private String password;
private Date birthday;
//代表当前用户具备哪些订单
private List<Order> orderList;
//代表当前用户具备哪些角色
private List<Role> roleList;
}
public class Role {
private int id;
private String rolename;
}
使用注解配置Mapper
public interface UserMapper {
@Select("select * from user")
@Results({
@Result(id = true,property = "id",column = "id"),
@Result(property = "username",column = "username"),
@Result(property = "password",column = "password"),
@Result(property = "birthday",column = "birthday"),
@Result(property = "roleList",column = "id",
javaType = List.class,
many = @Many(select = "com.itheima.mapper.RoleMapper.findByUid"))
})
List<User> findAllUserAndRole();}
}
public interface RoleMapper {
@Select("select * from role
r,user_role ur where
r.id=ur.role_id and
ur.user_id=#{uid}")
List<Role> findByUid(int uid);
}
测试结果
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> all = mapper.findAllUserAndRole();
for(User user : all){
System.out.println(user.getUsername());
List<Role> roleList = user.getRoleList();
for(Role role : roleList){
System.out.println(role);
}
System.out.println("----------------------------------");
}