MyBatis(五天掌握之第二天)
作者:互联网
-
MyBatis巩固步骤:
- 编写JavaBean:为每一张表编写对应的JavaBean
- 编写业务类Mapper
- 编写核心配置文件
- 编写测试类
-
Mapper
//1 只需要编辑接口 //2 编写功能方法,并为每一个方法添加功能注解 // 常见注解 @Select //查询,方法返回值:JavaBean、List<JavaBean>、Map等 @Insert //添加,方法返回值:Integer @Update //更新,方法返回值:Integer @Delete //删除,方法返回值:Integer
-
测试类
//1 加载配置文件 InputStream is = Resources.getSourceAsStream("xxx.xml"); //2 获得工厂 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is); //3 通过工厂获得会话(连接) SqlSession session = factory.openSession(); //4 通过会话获得功能接口 UserMapper userMapper = session.getMapper(UserMapper.class); //5 执行功能方法 // 提交事务 session.commit(); //6 处理结果 //7 释放资源 session.close();
1.核心配置文件详解
1.1 properties
-
使用 properties 抽取经常修改的内容
-
方式1:直接抽取
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-p0mVYRrY-1633393234271)(assets/image-20210926152505930.png)]
<!-- properties方式1:抽取数据库配置 --> <properties> <property name="jdbc.driver" value="com.mysql.cj.jdbc.Driver"/> <property name="jdbc.url" value="jdbc:mysql://localhost:3306/ssm_db1"/> <property name="jdbc.username" value="root"/> <property name="jdbc.password" value="1234"/> </properties> <!-- 环境: default的值引用什么id,就表示使用什么数据库了--> <environments default="db1"> <!-- 配置数据库连接信息及事务 --> <environment id="db1"> <!-- 表示使用事务:默认是自动开启事务 --> <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>
-
方式2:将进行修改的内容抽取到properties文件中
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssm_db1 jdbc.username=root jdbc.password=1234
<properties resource="db.properties"/>
1.2 settings
-
开启驼峰映射
<!-- 系统参数设置 --> <settings> <!-- 驼峰映射: 数据库字段:user_name java驼峰命名:userName --> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings>
1.3 mappers
-
加载一个类
<mappers> <!-- 加载一个功能接口 --> <mapper class="com.czxy.ssm.mapper.UserMapper"/> </mappers>
-
加载一个包
<mappers> <!-- 表示加载此包下的所有dao接口--> <package name="com.czxy.ssm.mapper"/> </mappers>
2 API详解
2.1 输入:vo条件
- 编写Vo,条件查询封装类
package com.czxy.ssm.vo;
/**
* @author LiReign
*/
public class UserVo {
private String beginTime;
private String endTime;
public String getBeginTime() {
return beginTime;
}
public void setBeginTime(String beginTime) {
this.beginTime = beginTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
}
- 编写功能接口
/**
* 条件查询
* @param userVo
* @return
*/
@Select("SELECT * FROM `user` WHERE birthday >= #{beginTime} AND birthday <= #{endTime}")
public List<User> condition(UserVo userVo);
- 测试
package com.czxy.ssm;
import com.czxy.ssm.domain.User;
import com.czxy.ssm.mapper.UserMapper;
import com.czxy.ssm.utils.MyBatisUtils;
import com.czxy.ssm.vo.UserVo;
import java.io.IOException;
import java.util.List;
/**
* @author LiReign
*/
public class Test06_Condition {
public static void main(String[] args) throws IOException {
//1 通过会话获得功能接口
UserMapper userMapper = MyBatisUtils.getMapper(UserMapper.class);
//2 更新
UserVo userVo = new UserVo();
userVo.setBeginTime("2010");
userVo.setEndTime("2020");
List<User> list = userMapper.condition(userVo);
// 打印结果
list.forEach(System.out::println);
//3 提交并关闭
MyBatisUtils.commitAndclose();
}
}
2.2 输出:结果集映射
-
结果集映射:查询结果 与 JavaBean之间的映射关系。表的列名和JavaBean的属性名对应关系。
-
@Results 用于配置JavaBean和表的映射关系的
- @Result 配置JavaBean一个属性和 表的一个列之间对应关系。
-
@ResultMap 共享已经映射关系
-
实例1:JavaBean和表映射关系
@Select("select * from user")
@Results({
@Result(column = "user_name",property = "userName"),
@Result(column = "password", property = "password")
})
public List<User> selectAll();
-
实例2:共享映射关系
@Select("SELECT * FROM `user` WHERE `name` LIKE '%${name}%'") @ResultMap("userResultMap") public List<User> selectByName(@Param("name") String name);
3. 多表操作:一对多
3.1 JavaBean
3.1.1 编写JavaBean:User
public class User {
private String uid;
private String userName;
private String password;
private String name;
private String email;
private Date birthday;
private String sex;
private Integer state;
private String code;
3.1.2 编写JavaBean:Order
public class Order {
private String oid; // 订单编号
private Date ordertime; // 下单时间
private Double total; // 订单总金额
private Integer state; // 订单状态 0 未支付 1 已支付 2已发货 3已收货
private String address; // 收货人地址
private String name; // 收货人姓名
private String telephone; // 收货人电话
private String uid;
3.1.3 编写对应关系
public class User {
// 一对多关系:一个用户拥有多个订单
private List<Order> orderList = new ArrayList<>()
3.2 编写各自Mapper
3.2.1 编写UserMapper
package com.czxy.ssm.mapper;
import com.czxy.ssm.domain.User;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* @author LiReign
*/
public interface UserMapper {
/**
* 查询所有
* @return
*/
@Select("select * from user")
@Results(id="userResultMap", value={
@Result(column = "user_name",property = "userName"),
@Result(column = "password", property = "password")
})
public List<User> selectAll();
}
3.2.2 编写OrderMapper
- 查询指定用户的所有的订单
package com.czxy.ssm.mapper;
import com.czxy.ssm.domain.Order;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* @author LiReign
*/
public interface OrderMapper {
/**
* 查询指定用户的所有订单
* @param uid
* @return
*/
@Select("SELECT * FROM orders WHERE uid = #{uid}")
public List<Order> selectAllByUid(@Param("uid") String uid);
}
3.3 测试类
3.3.1 user测试
package com.czxy.ssm;
import com.czxy.ssm.domain.User;
import com.czxy.ssm.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 java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* @author LiReign
*/
public class Test01_SelectAll {
public static void main(String[] args) throws IOException {
//1 加载配置文件
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
//2 获得工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//3 通过工程获得会话(连接)
SqlSession sqlSession = factory.openSession();
//4 获得功能接口
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//5 进行查询
List<User> list = userMapper.selectAll();
//6 处理数据
for(User user: list) {
System.out.println(user);
}
//7 释放资源
sqlSession.close();
}
}
3.3.2 order测试
package com.czxy.ssm;
import com.czxy.ssm.domain.Order;
import com.czxy.ssm.domain.User;
import com.czxy.ssm.mapper.OrderMapper;
import com.czxy.ssm.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 java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* @author LiReign
*/
public class Test02_SelectAllOrderByUId {
public static void main(String[] args) throws IOException {
//1 加载配置文件
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
//2 获得工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//3 通过工程获得会话(连接)
SqlSession sqlSession = factory.openSession();
//4 获得功能接口
OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
//5 进行查询
List<Order> list = orderMapper.selectAllByUid("u001");
//6 处理数据
list.forEach(System.out::println);
//7 释放资源
sqlSession.close();
}
}
3.4 映射关系
- 查询所有用户的同时,关联查询每一个用户的所有的订单。
package com.czxy.ssm.mapper;
import com.czxy.ssm.domain.User;
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;
/**
* @author LiReign
*/
public interface UserMapper {
/**
* 查询所有
* @return
*/
@Select("select * from user")
@Results(id="userResultMap", value={
@Result(property = "uid", column = "uid"),
@Result(property = "userName", column = "user_name"),
@Result(property = "password", column = "password"),
@Result(property = "orderList",column = "uid", many=@Many(select = "com.czxy.ssm.mapper.OrderMapper.selectAllByUid"))
})
public List<User> selectAll();
}
4. 多表操作:多对一
4.1 分析
- 目标:查询订单的同时,可以查询所有的用户
- 步骤:
- 修改OrderMapper,通过id查询订单详情
- 测试类 order详情
- 修改Order,添加User属性
- 修改UserMapper,通过id查询用户详情
- 修改OrderMapper,建立关联
4.2 OrderMapper 详情
public interface OrderMapper {
/**
* 查询详情
* @param oid
* @return
*/
@Select("select * from orders where oid = #{oid}")
public Order selectById(@Param("oid") String oid);
}
4.3 测试类 order详情
package com.czxy.ssm;
import com.czxy.ssm.domain.Order;
import com.czxy.ssm.mapper.OrderMapper;
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.InputStream;
import java.util.List;
/**
* @author LiReign
*/
public class Test03_SelectOrderByOId {
public static void main(String[] args) throws IOException {
//1 加载配置文件
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
//2 获得工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//3 通过工程获得会话(连接)
SqlSession sqlSession = factory.openSession();
//4 获得功能接口
OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
//5 进行查询
Order order = orderMapper.selectById("x001");
//6 处理数据
System.out.println(order);
//7 释放资源
sqlSession.close();
}
}
4.4 修改Order
public class Order { // 多对一:多个订单属于一个用户 private User user;
4.5 UserMapper 详情
public interface UserMapper {
/**
* 通过uid查询详情
* @param uid
* @return
*/
@Select("select * from user where uid = #{uid}")
public User selectById(@Param("uid") String uid);
}
4.6 修改OrderMapper,建立关联
package com.czxy.ssm.mapper;
import com.czxy.ssm.domain.Order;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* @author LiReign
*/
public interface OrderMapper {
/**
* 查询详情
* @param oid
* @return
*/
@Select("select * from orders where oid = #{oid}")
@Results({
@Result(property = "user", column = "uid" , one = @One(select="com.czxy.ssm.mapper.UserMapper.selectById"))
})
public Order selectById(@Param("oid") String oid);
}
标签:String,ssm,第二天,五天,MyBatis,import,com,public,czxy 来源: https://blog.csdn.net/LiReign/article/details/120610601