• MyBatis框架 注解的形式开发


    目录

    1.注解开发项目整体框架(与xml形式开发 在resource里面 没了xxxmapper.xml)

    2.配置资源

    (1)jdbc.properties

     (2)SqlMapConfig.xml

    3.实体类

    (1)User

    (2)Order

    (3)Role

    4.SqlSessionutils 工具类

    5.mapper 接口

    (1)UserMapper

    (2)OrderMapper

    (3)RoleMapper

    6.数据库信息(创建并使用数据库 然后先创建user表 在创建其他的)

    7.测试

    (1)一对一查询,查询一个订单,与此同时查询出该订单所属的用户

    测试代码

    (2)一对多查询,查询一个用户,与此同时查询出该用户具有的订单

     测试语句

    (3)多对多查询 ,查询所有用户,同时查询出该用户的所有角色

    sql语句

    测试语句



    1.注解开发项目整体框架(与xml形式开发 在resource里面 没了xxxmapper.xml)

    * @Insert:实现新增,代替了<insert></insert>
    * @Delete:实现删除,代替了<delete></delete>
    * @Update:实现更新,代替了<update></update>
    * @Select:实现查询,代替了<select></select>
    * @Result:实现结果集封装,代替了<result></result>
    * @Results:可以与@Result 一起使用,封装多个结果集,代替了<resultMap></resultMap>
    * @One:实现一对一结果集封装,代替了<association></association>
    * @Many:实现一对多结果集封装,代替了<collection></collection>

    2.配置资源

    (1)jdbc.properties

    1. jdbc.driver=com.mysql.jdbc.Driver
    2. jdbc.url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=true
    3. jdbc.username=root
    4. jdbc.password=root

     (2)SqlMapConfig.xml

    1. <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    2. "http://mybatis.org/dtd/mybatis-3-config.dtd">
    3. <configuration>
    4. <!-- 加载外部的配置文件-->
    5. <properties resource="jdbc.properties"></properties>
    6. <settings>
    7. <!-- 控制台 打印sql -->
    8. <setting name="logImpl" value="STDOUT_LOGGING"/>
    9. </settings>
    10. <!-- 别名配置-->
    11. <typeAliases>
    12. <typeAlias type="com.qiku.pojo.User" alias="user"></typeAlias>
    13. <typeAlias type="com.qiku.pojo.Order" alias="order"></typeAlias>
    14. <typeAlias type="com.qiku.pojo.Role" alias="role"></typeAlias>
    15. </typeAliases>
    16. <!-- 配置数据库环境 default 可以自定义-->
    17. <environments default="MYSQL">
    18. <environment id="MYSQL">
    19. <transactionManager type="JDBC"></transactionManager>
    20. <dataSource type="POOLED">
    21. <property name="driver" value="${jdbc.driver}"/>
    22. <property name="url" value="${jdbc.url}"/>
    23. <property name="username" value="${jdbc.username}"/>
    24. <property name="password" value="${jdbc.password}"/>
    25. </dataSource>
    26. </environment>
    27. </environments>
    28. <!-- 核心配置文件加载OrderMapper.xml-->
    29. <mappers>
    30. <!-- resource 属性实现-->
    31. <!-- <mapper resource="com/qiku/mapper/UserMapper.xml"></mapper>-->
    32. <!-- <mapper resource="com/qiku/mapper/OrderMapper.xml"></mapper>-->
    33. <!-- <mapper resource="com/qiku/mapper/RoleMapper.xml"></mapper>-->
    34. <!-- //用包名-->
    35. <package name="com.qiku.mapper"/>
    36. </mappers>
    37. </configuration>

    3.实体类

    (1)User

    1. package com.qiku.pojo;
    2. import java.io.Serializable;
    3. import java.util.Date;
    4. import java.util.List;
    5. /**
    6. * 2022/6/16 20:46
    7. *
    8. * @author yrc
    9. * @version MybatisTest
    10. */
    11. public class User implements Serializable {
    12. private Integer id;
    13. private String username;
    14. private Date birthday;
    15. private String sex;
    16. private String address;
    17. public User(String username, Date birthday, String sex, String address) {
    18. this.username = username;
    19. this.birthday = birthday;
    20. this.sex = sex;
    21. this.address = address;
    22. }
    23. // 一对多
    24. private List<Order> orderList;
    25. private List<Role> roleList;
    26. public List<Role> getRoleList() {
    27. return roleList;
    28. }
    29. public void setRoleList(List<Role> roleList) {
    30. this.roleList = roleList;
    31. }
    32. public List<Order> getOrderList() {
    33. return orderList;
    34. }
    35. public void setOrderList(List<Order> orderList) {
    36. this.orderList = orderList;
    37. }
    38. public Integer getId() {
    39. return id;
    40. }
    41. public void setId(Integer id) {
    42. this.id = id;
    43. }
    44. public String getUsername() {
    45. return username;
    46. }
    47. public void setUsername(String username) {
    48. this.username = username;
    49. }
    50. public Date getBirthday() {
    51. return birthday;
    52. }
    53. public void setBirthday(Date birthday) {
    54. this.birthday = birthday;
    55. }
    56. public String getSex() {
    57. return sex;
    58. }
    59. public void setSex(String sex) {
    60. this.sex = sex;
    61. }
    62. public String getAddress() {
    63. return address;
    64. }
    65. public void setAddress(String address) {
    66. this.address = address;
    67. }
    68. public User() {
    69. }
    70. public User(Integer id, String username, Date birthday, String sex, String address, List<Order> orderList) {
    71. this.id = id;
    72. this.username = username;
    73. this.birthday = birthday;
    74. this.sex = sex;
    75. this.address = address;
    76. this.orderList = orderList;
    77. }
    78. @Override
    79. public String toString() {
    80. return "User{" +
    81. "id=" + id +
    82. ", username='" + username + '\'' +
    83. ", birthday=" + birthday +
    84. ", sex='" + sex + '\'' +
    85. ", address='" + address + '\'' +
    86. ", orderList=" + orderList +
    87. ", roleList=" + roleList +
    88. '}';
    89. }
    90. }

    (2)Order

    1. package com.qiku.pojo;
    2. import java.io.Serializable;
    3. import java.util.Date;
    4. /**
    5. * 2022/6/21 15:54
    6. *
    7. * @author yrc
    8. * @version Mybatis
    9. */
    10. public class Order implements Serializable {
    11. private Integer id;
    12. private Date orderTime;
    13. private double money;
    14. // 表示当前订单属于哪个用户
    15. private User user;
    16. @Override
    17. public String toString() {
    18. return "Order{" +
    19. "id=" + id +
    20. ", orderTime=" + orderTime +
    21. ", money=" + money +
    22. ", user=" + user +
    23. '}';
    24. }
    25. public Order() {
    26. }
    27. public Order(Integer id, Date orderTime, double money, User user) {
    28. this.id = id;
    29. this.orderTime = orderTime;
    30. this.money = money;
    31. this.user = user;
    32. }
    33. public Integer getId() {
    34. return id;
    35. }
    36. public void setId(Integer id) {
    37. this.id = id;
    38. }
    39. public Date getOrderTime() {
    40. return orderTime;
    41. }
    42. public void setOrderTime(Date orderTime) {
    43. this.orderTime = orderTime;
    44. }
    45. public double getMoney() {
    46. return money;
    47. }
    48. public void setMoney(double money) {
    49. this.money = money;
    50. }
    51. public User getUser() {
    52. return user;
    53. }
    54. public void setUser(User user) {
    55. this.user = user;
    56. }
    57. }

    (3)Role

    1. package com.qiku.pojo;
    2. /**
    3. * 2022/6/22 9:38
    4. *
    5. * @author yrc
    6. * @version Mybatis
    7. */
    8. public class Role {
    9. private Integer id;
    10. private String roleName;
    11. private String roleDesc;
    12. @Override
    13. public String toString() {
    14. return "Role{" +
    15. "id=" + id +
    16. ", roleName='" + roleName + '\'' +
    17. ", roleDesc='" + roleDesc + '\'' +
    18. '}';
    19. }
    20. public Integer getId() {
    21. return id;
    22. }
    23. public void setId(Integer id) {
    24. this.id = id;
    25. }
    26. public String getRoleName() {
    27. return roleName;
    28. }
    29. public void setRoleName(String roleName) {
    30. this.roleName = roleName;
    31. }
    32. public String getRoleDesc() {
    33. return roleDesc;
    34. }
    35. public void setRoleDesc(String roleDesc) {
    36. this.roleDesc = roleDesc;
    37. }
    38. public Role() {
    39. }
    40. public Role(Integer id, String roleName, String roleDesc) {
    41. this.id = id;
    42. this.roleName = roleName;
    43. this.roleDesc = roleDesc;
    44. }
    45. }

    4.SqlSessionutils 工具类

    12.SqlSession 的工具类 获取sqlsession_羊肉串学爪哇的博客-CSDN博客

    5.mapper 接口

    (1)UserMapper

    1. package com.qiku.mapper;
    2. import com.qiku.pojo.Order;
    3. import com.qiku.pojo.User;
    4. import org.apache.ibatis.annotations.*;
    5. import org.apache.ibatis.mapping.FetchType;
    6. import java.util.List;
    7. /**
    8. * 2022/6/22 10:35
    9. *
    10. * @author yrc
    11. * @version Mybatis
    12. */
    13. @CacheNamespace
    14. public interface UserMapper {
    15. @Insert("insert into user(username,birthday,sex,address) " +
    16. "values(#{username},#{birthday},#{sex},#{address})")
    17. public void addUser(User user);
    18. @Delete("delete from user where id=#{id}")
    19. public void deleteUser(Integer id);
    20. @Update("update user set username=#{username} where id=#{id}")
    21. public void updateUser(User user);
    22. @Select("select * from user")
    23. public List<User> selectUser();
    24. @Select("select * from user where id=#{id}")
    25. public User findUserById(Integer id);
    26. @Select("select * from user")
    27. @Results({
    28. @Result(id=true ,column = "id",property ="id"),
    29. @Result(column = "username" ,property="username"),
    30. @Result(column = "birthday" ,property="birthday"),
    31. @Result(column = "sex" ,property="sex"),
    32. @Result(column = "address" ,property="address"),
    33. @Result(column = "id",property ="orderList",javaType = List.class,
    34. many = @Many(select = "com.qiku.mapper.OrderMapper.findOrderByUid",
    35. fetchType = FetchType.EAGER))
    36. })
    37. //一对多
    38. public List<User> findAllUserWithOrder();
    39. //查询所有用户以及角色信息
    40. @Select("select * from user")
    41. @Results({
    42. @Result(id=true ,column = "id",property ="id"),
    43. @Result(column = "username" ,property="username"),
    44. @Result(column = "birthday" ,property="birthday"),
    45. @Result(column = "sex" ,property="sex"),
    46. @Result(column = "address" ,property="address"),
    47. @Result(column = "id",property ="roleList",javaType = List.class,
    48. many = @Many(select = "com.qiku.mapper.RoleMapper.findRoleByUid",
    49. fetchType = FetchType.EAGER))
    50. })
    51. public List<User> findAllUserWithRole();
    52. }

    (2)OrderMapper

    1. package com.qiku.mapper;
    2. import com.qiku.pojo.Order;
    3. import com.qiku.pojo.User;
    4. import net.sf.jsqlparser.schema.Column;
    5. import org.apache.ibatis.annotations.One;
    6. import org.apache.ibatis.annotations.Result;
    7. import org.apache.ibatis.annotations.Results;
    8. import org.apache.ibatis.annotations.Select;
    9. import org.apache.ibatis.mapping.FetchType;
    10. import java.util.List;
    11. /**
    12. * 2022/6/22 11:10
    13. *
    14. * @author yrc
    15. * @version Mybatis
    16. */
    17. public interface OrderMapper {
    18. // 查询所有订单以及订单的用户信息
    19. @Select("select * from orders ")
    20. @Results({
    21. // 主键 数据库字段 实体类字段
    22. @Result(id=true ,column = "id" ,property="id"),
    23. // 数据库字段 实体类字段
    24. @Result(column = "ordertime" ,property="orderTime"),
    25. @Result(column = "total" ,property="money"),
    26. @Result(column = "uid",property ="user",javaType = User.class,
    27. one = @One(select = "com.qiku.mapper.UserMapper.findUserById",
    28. fetchType = FetchType.EAGER)
    29. )
    30. })
    31. public List<Order> findAllOrderWithUser();
    32. @Select("select * from orders where id=#{uid}")
    33. @Results({
    34. @Result(id =true,column = "id" ,property = "id"),
    35. @Result(column = "ordertime",property = "orderTime"),
    36. @Result(column = "total",property = "money")
    37. })
    38. public List<Order> findOrderByUid(Integer uid);
    39. }

    (3)RoleMapper

    1. package com.qiku.mapper;
    2. import com.qiku.pojo.Role;
    3. import org.apache.ibatis.annotations.Select;
    4. import java.util.List;
    5. /**
    6. * 2022/6/22 15:18
    7. *
    8. * @author yrc
    9. * @version Mybatis
    10. */
    11. public interface RoleMapper {
    12. @Select("select * from sys_role r LEFT JOIN sys_user_role ur\n" +
    13. "on r.id = ur.roleid WHERE ur.userid = #{userId}")
    14. public List<Role> findRoleByUid(Integer userId);
    15. }

    6.数据库信息(创建并使用数据库 然后先创建user表 在创建其他的)

    1. SET NAMES utf8mb4;
    2. SET FOREIGN_KEY_CHECKS = 0;
    3. -- ----------------------------
    4. -- Table structure for orders
    5. -- ----------------------------
    6. DROP TABLE IF EXISTS `orders`;
    7. CREATE TABLE `orders` (
    8. `id` int(11) NOT NULL AUTO_INCREMENT,
    9. `ordertime` varchar(255) DEFAULT NULL,
    10. `total` double DEFAULT NULL,
    11. `uid` int(11) DEFAULT NULL,
    12. PRIMARY KEY (`id`),
    13. KEY `uid` (`uid`),
    14. CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`uid`) REFERENCES `user` (`id`)
    15. ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
    16. -- ----------------------------
    17. -- Records of orders
    18. -- ----------------------------
    19. BEGIN;
    20. INSERT INTO `orders` VALUES (1, '2022-12-12', 3000, 1);
    21. INSERT INTO `orders` VALUES (2, '2022-12-12', 4000, 1);
    22. INSERT INTO `orders` VALUES (3, '2022-12-12', 5000, 2);
    23. COMMIT;
    24. -- ----------------------------
    25. -- Table structure for store
    26. -- ----------------------------
    27. DROP TABLE IF EXISTS `store`;
    28. CREATE TABLE `store` (
    29. `id` int(11) NOT NULL AUTO_INCREMENT,
    30. `shop_owner` varchar(32) DEFAULT NULL COMMENT '店主姓名',
    31. `id_number` varchar(18) DEFAULT NULL COMMENT '身份证号',
    32. `name` varchar(100) DEFAULT NULL COMMENT '店铺名称',
    33. `industry` varchar(100) DEFAULT NULL COMMENT '行业分类',
    34. `area` varchar(200) DEFAULT NULL COMMENT '店铺区域',
    35. `phone` varchar(11) DEFAULT NULL COMMENT '手机号码',
    36. `status` int(11) DEFAULT '0' COMMENT '审核状态。 0:待审核 1:审核通过 2:审核失败 3:重新审核 ',
    37. `audit_time` datetime DEFAULT NULL COMMENT '审核时间',
    38. PRIMARY KEY (`id`)
    39. ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4;
    40. -- ----------------------------
    41. -- Records of store
    42. -- ----------------------------
    43. BEGIN;
    44. INSERT INTO `store` VALUES (1, '张三丰', '441322199309273014', '张三丰包子铺', '美食', '北京市海淀区', '18933283299', 0, '2017-12-08 12:35:30');
    45. INSERT INTO `store` VALUES (2, '令狐冲', '441322199009102104', '华冲手机维修', '电子维修', '北京市昌平区', '18933283299', 1, '2019-01-20 20:20:00');
    46. INSERT INTO `store` VALUES (3, '赵敏', '441322199610205317', '托尼美容美发', '美容美发', '北京市朝阳区', '18933283299', 2, '2020-08-08 10:00:30');
    47. INSERT INTO `store` VALUES (5, '齐云霄', '1111', '云霄子阁', '阵法专卖', '元武国', '110', 0, '2022-06-20 10:30:29');
    48. INSERT INTO `store` VALUES (8, '齐云霄', '1111', '云霄阁', '阵法专卖', '元武国', '110', 0, '2022-06-21 09:46:42');
    49. COMMIT;
    50. -- ----------------------------
    51. -- Table structure for sys_role
    52. -- ----------------------------
    53. DROP TABLE IF EXISTS `sys_role`;
    54. CREATE TABLE `sys_role` (
    55. `id` int(11) NOT NULL AUTO_INCREMENT,
    56. `rolename` varchar(255) DEFAULT NULL,
    57. `roleDesc` varchar(255) DEFAULT NULL,
    58. PRIMARY KEY (`id`)
    59. ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
    60. -- ----------------------------
    61. -- Records of sys_role
    62. -- ----------------------------
    63. BEGIN;
    64. INSERT INTO `sys_role` VALUES (1, 'CTO', 'CTO');
    65. INSERT INTO `sys_role` VALUES (2, 'CEO', 'CEO');
    66. COMMIT;
    67. -- ----------------------------
    68. -- Table structure for sys_user_role
    69. -- ----------------------------
    70. DROP TABLE IF EXISTS `sys_user_role`;
    71. CREATE TABLE `sys_user_role` (
    72. `userid` int(11) NOT NULL,
    73. `roleid` int(11) NOT NULL,
    74. PRIMARY KEY (`userid`,`roleid`),
    75. KEY `roleid` (`roleid`),
    76. CONSTRAINT `sys_user_role_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `user` (`id`),
    77. CONSTRAINT `sys_user_role_ibfk_2` FOREIGN KEY (`roleid`) REFERENCES `sys_role` (`id`)
    78. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    79. -- ----------------------------
    80. -- Records of sys_user_role
    81. -- ----------------------------
    82. BEGIN;
    83. INSERT INTO `sys_user_role` VALUES (1, 1);
    84. INSERT INTO `sys_user_role` VALUES (2, 1);
    85. INSERT INTO `sys_user_role` VALUES (1, 2);
    86. INSERT INTO `sys_user_role` VALUES (2, 2);
    87. COMMIT;
    88. -- ----------------------------
    89. -- Table structure for user
    90. -- ----------------------------
    91. DROP TABLE IF EXISTS `user`;
    92. CREATE TABLE `user` (
    93. `id` int(11) NOT NULL AUTO_INCREMENT,
    94. `username` varchar(32) NOT NULL COMMENT '用户名称',
    95. `birthday` datetime DEFAULT NULL COMMENT '生日',
    96. `sex` char(1) DEFAULT NULL COMMENT '性别',
    97. `address` varchar(256) DEFAULT NULL COMMENT '地址',
    98. PRIMARY KEY (`id`)
    99. ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
    100. -- ----------------------------
    101. -- Records of user
    102. -- ----------------------------
    103. BEGIN;
    104. INSERT INTO `user` VALUES (1, '张三', '2020-11-11 00:00:00', '男', '北京海淀');
    105. INSERT INTO `user` VALUES (2, '李四', '2020-12-12 00:00:00', '男', '北京海淀');
    106. COMMIT;
    107. SET FOREIGN_KEY_CHECKS = 1;

    7.测试

    (1)一对一查询,查询一个订单,与此同时查询出该订单所属的用户

    测试代码

    1. @Test
    2. public void testFindAllOrderWithUser(){
    3. SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    4. OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
    5. List<Order> orderList = mapper.findAllOrderWithUser();
    6. for(Order order:orderList){
    7. System.out.println(order);
    8. }
    9. }

    (2)一对多查询,查询一个用户,与此同时查询出该用户具有的订单

     测试语句

    1. @Test
    2. public void findAllUserWithOrder(){
    3. SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    4. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    5. List<User> allUserWithOrder = mapper.findAllUserWithOrder();
    6. for(User user:allUserWithOrder){
    7. System.out.println(user);
    8. }
    9. }

    (3)多对多查询 ,查询所有用户,同时查询出该用户的所有角色

    sql语句

    1. SELECT * FROM `user`;
    2. SELECT * FROM role r INNER JOIN user_role ur ON r.`id` = ur.`rid`
    3. WHERE ur.`uid` = #{id};

    测试语句

    1. @Test
    2. public void findAllUserWithRole(){
    3. SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    4. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    5. List<User> allUserWithRole = mapper.findAllUserWithRole();
    6. for(User user:allUserWithRole){
    7. System.out.println(user);
    8. }
    9. }

  • 相关阅读:
    java计算机毕业设计医疗器械销售电子商城源码+系统+mysql数据库+lw文档
    Linux:进程的本质和fork初识
    化妆品展示网页设计作业 静态HTML化妆品网站 DW美妆网站模板下载 大学生简单网页作品代码 个人网页制作 学生个人网页设计作业
    【考研】操作系统——同步互斥问题(P、V操作)3
    Flink学习:Flink支持的数据类型
    代码随想录笔记_动态规划_337打家劫舍III
    java计算机毕业设计化妆品销售网站源码+mysql数据库+系统+lw文档+部署
    基于Internet应用的分销ERP系统源码
    ChatTTS web应用;基于文本指导的图像生成;使用Groq和Llama3在几秒内生成整本书;协作机器人画家,可以根据语言描述或图像在画布上作画
    【GEE】6、在 Google 地球引擎中构建各种遥感指数
  • 原文地址:https://blog.csdn.net/weixin_45172902/article/details/125435516