Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How Mybatis implements one-to-one and one-to-many associative queries using @ one and @ Many

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Many novices are not very clear about how Mybatis uses @ one and @ Many to implement one-to-one and one-to-many related queries. In order to help you solve this problem, the following editor will explain it in detail. People with this need can come and learn. I hope you can get something.

First, the preparatory work 1. Create a springboot project with the following structure

two。 Add pom.xml configuration information org.mybatis mybatis 3.4.2 org.mybatis.spring.boot mybatis-spring-boot-starter 1.3.0 mysql mysql-connector-java 5.1.34 3. Configuration related information

Modify the suffix of the default application.properties file to ".yml", that is, the configuration file name is: application.yml, and configure the following information:

Spring: # DataSource data source datasource: url: jdbc:mysql://localhost:3306/mybatis_test?useSSL=false& username: root password: root driver-class-name: com.mysql.jdbc.Driver#MyBatis configuration mybatis: type-aliases-package: com.mye.hl07mybatis.api.pojo # alias definition configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # specify the specific implementation of the log used by MyBatis Map-underscore-to-camel-case is automatically found when not specified: true # enables automatic hump naming rule (camel case) mapping lazy-loading-enabled: true # turns on delay loading switch aggressive-lazy-loading: false # changes positive loading to negative loading (that is, on-demand loading). The default value is false lazy-load-trigger-methods: "# blocking irrelevant operation triggers Implement lazy loading cache-enabled: true # turn on the global cache switch (secondary environment). The default value is true 2. Use @ One annotation to implement one-to-one relational query.

Requirements: get user information and get a list of one-to-many associated permissions

1. Create a user information table (tb_user) in the MySQL database

-- determine whether the data table exists, and delete the DROP TABLE IF EXISTS tb_user if it exists. -- create "user Information" data sheet CREATE TABLE IF NOT EXISTS tb_user (user_id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'user number', user_account VARCHAR (50) NOT NULL COMMENT 'user account', user_password VARCHAR (50) NOT NULL COMMENT 'user password', blog_url VARCHAR (50) NOT NULL COMMENT 'blog address' Remark VARCHAR (50) COMMENT 'remarks') COMMENT = 'user information table' -- add data INSERT INTO tb_user (user_account,user_password,blog_url,remark) VALUES ('blog refusing to stay up late', '123456' https://blog.csdn.net/weixin_43296313/','', Welcome to visit blog that refuses to stay up late)

two。 Create ID card information table (tb_idcard) in MySQL database

-- determine whether the data table exists, then delete DROP TABLE IF EXISTS tb_idcard;-- create the "ID card information" data table CREATE TABLE IF NOT EXISTS tb_idcard (id INT AUTO_INCREMENT PRIMARY KEY COMMENT'ID card ID', user_id INT NOT NULL COMMENT 'user number', idCard_code VARCHAR (45) COMMENT'ID card number') COMMENT = "ID card information table" -- add data INSERT INTO tb_idcard (user_id,idCard_code) VALUE (1meme 123456789')

3. Create a user information persistence class (UserInfo.java)

@ Data@AllArgsConstructor@NoArgsConstructorpublic class UserInfo {private int userId; / / user ID private String userAccount; / / user account private String userPassword; / / user password private String blogUrl; / / blog address private String remark; / / remarks private IdcardInfo idcardInfo; / / ID card information}

4. Create a persistence class for ID card information (IdcardInfo.java)

@ Data@AllArgsConstructor@NoArgsConstructorpublic class IdcardInfo {public int id; / / ID card ID public int userId; / / user ID public String idCardCode; / / ID card number}

5. Create UserMapper interface (Mapper dynamic proxy interface for user information)

@ Repository@Mapperpublic interface UserMapper {/ * get user information and ID card information * one-to-one related query * / @ Select ("SELECT * FROM tb_user WHERE user_id = # {userId}") @ Results (id = "userAndIdcardResultMap", value = {@ Result (property = "userId", column = "user_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER, id = true) @ Result (property = "userAccount", column = "user_account", javaType = String.class, jdbcType = JdbcType.VARCHAR), @ Result (property = "userPassword", column = "user_password", javaType = String.class, jdbcType = JdbcType.VARCHAR), @ Result (property = "blogUrl", column = "blog_url", javaType = String.class, jdbcType = JdbcType.VARCHAR), @ Result (property = "remark", column = "remark" JavaType = String.class, jdbcType = JdbcType.VARCHAR), @ Result (property = "idcardInfo", column = "user_id", one = @ One (select = "com.mye.hl07mybatis.api.mapper.UserMapper.getIdcardInfo", fetchType = FetchType.LAZY)}) UserInfo getUserAndIdcardInfo (@ Param ("userId") int userId) / * according to the user ID Obtain ID card information * / @ Select ("SELECT * FROM tb_idcard WHERE user_id = # {userId}") @ Results (id = "idcardInfoResultMap", value = {@ Result (property = "id", column = "id"), @ Result (property = "userId", column = "user_id"), @ Result (property = "idCardCode") Column = "idCard_code")}) IdcardInfo getIdcardInfo (@ Param ("userId") int userId) }

6. Implement the mapping relationship between entity classes and data tables

Add @ MapperScan (basePackages = "com.mye.hl07mybatis.api.mapper") to the SpringBoot startup class.

@ SpringBootApplication@MapperScan (basePackages = "com.mye.hl07mybatis.api.mapper") public class Hl07MybatisApplication {public static void main (String [] args) {SpringApplication.run (Hl07MybatisApplication.class, args);}}

7. Write an execution method to obtain user information and ID card information (one-to-one related query)

@ SpringBootTest (classes = Hl07MybatisApplication.class) @ RunWith (SpringRunner.class) public class Hl07MybatisApplicationTests {@ Autowired private UserMapper userMapper; / * get user information and ID card information * one-to-one related query * @ author pan_junbiao * / @ Test public void getUserAndIdcardInfo () {/ / execute the query method of Mapper proxy object UserInfo userInfo = userMapper.getUserAndIdcardInfo (1) / / print result if {System.out.println ("user ID:" + userInfo.getUserId ()); System.out.println ("user account:" + userInfo.getUserAccount ()); System.out.println ("user password:" + userInfo.getUserPassword ()); System.out.println ("blog address:" + userInfo.getBlogUrl ()) System.out.println ("remarks:" + userInfo.getRemark ()); System.out.println ("- -"); / / get ID card information IdcardInfo idcardInfo = userInfo.getIdcardInfo () If {System.out.println ("ID card ID:" + idcardInfo.getId ()); System.out.println ("user ID:" + idcardInfo.getUserId ()); System.out.println ("ID card number:" + idcardInfo.getIdCardCode ());}

Execution result:

Third, use @ Many annotation to implement one-to-many associative query

Requirements: get user information and get a list of one-to-many associated permissions

1. Create a permission information table (tb_role) in the MySQL database

-- determine whether the data table exists, and delete DROP TABLE IF EXISTS tb_role; if it exists-- create the "permission information" data table CREATE TABLE IF NOT EXISTS tb_role (id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'permission ID', user_id INT NOT NULL COMMENT' user number', role_name VARCHAR (50) NOT NULL COMMENT 'permission name') COMMENT = "permission information table" INSERT INTO tb_role (user_id,role_name) VALUES (1) 'system administrator'), (1 'news administrator'), (1 'advertisement administrator')

two。 Create a permission information persistence class (RoleInfo.java)

@ Data@AllArgsConstructor@NoArgsConstructorpublic class RoleInfo {private int id; / / permission ID private int userId; / / user number private String roleName; / / permission name}

3. Modify the user information persistence class (UserInfo.java) to add the property field of the permission list

@ Data@AllArgsConstructor@NoArgsConstructorpublic class UserInfo {private int userId; / / user ID private String userAccount; / / user account private String userPassword; / / user password private String blogUrl; / / blog address private String remark; / / remarks private IdcardInfo idcardInfo; / / ID card information private List roleInfoList; / / permission list}

4. Write Mapper dynamic proxy interface (UserMapper.java) for user information

/ * * get user information and permission list * one-to-many related query * @ author pan_junbiao * / @ Select ("SELECT * FROM tb_user WHERE user_id = # {userId}") @ Results (id = "userAndRolesResultMap", value = {@ Result (property = "userId", column = "user_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER, id = true), @ Result (property = "userAccount", column = "user_account") JavaType = String.class, jdbcType = JdbcType.VARCHAR), @ Result (property = "userPassword", column = "user_password", javaType = String.class, jdbcType = JdbcType.VARCHAR), @ Result (property = "blogUrl", column = "blog_url", javaType = String.class, jdbcType = JdbcType.VARCHAR), @ Result (property = "remark", column = "remark", javaType = String.class, jdbcType = JdbcType.VARCHAR), @ Result (property = "roleInfoList") Column = "user_id", many = @ Many (select = "com.pjb.mapper.UserMapper.getRoleList", fetchType = FetchType.LAZY)}) public UserInfo getUserAndRolesInfo (@ Param ("userId") int userId) / * according to the user ID Get permission list * @ author pan_junbiao * / @ Select ("SELECT * FROM tb_role WHERE user_id = # {userId}") @ Results (id = "roleInfoResultMap", value = {@ Result (property = "id", column = "id"), @ Result (property = "userId", column = "user_id"), @ Result (property = "roleName", column = "role_name")) public List getRoleList (@ Param ("userId") int userId)

5. Write execution methods to get user information and permission list (one-to-many associated queries)

/ * get user information and permission list * one-to-many association query * @ author pan_junbiao * / @ Test public void getUserAndRolesInfo () {/ / execute the query method of Mapper proxy object UserInfo userInfo = userMapper.getUserAndRolesInfo (1) / / print result if {System.out.println ("user ID:" + userInfo.getUserId ()); System.out.println ("user account:" + userInfo.getUserAccount ()); System.out.println ("user password:" + userInfo.getUserPassword ()); System.out.println ("blog address:" + userInfo.getBlogUrl ()) System.out.println ("remarks:" + userInfo.getRemark ()); System.out.println ("- -"); / / get permission list List roleInfoList = userInfo.getRoleInfoList () If (roleInfoListrated permissions null & & roleInfoList.size () > 0) {System.out.println ("permissions owned by the user:"); for (RoleInfo roleInfo: roleInfoList) {System.out.println (roleInfo.getRoleName ());}}

Execution result:

IV. The difference between FetchType.LAZY and FetchType.EAGER

FetchType.LAZY: lazy loading. Properties that define lazy loading are not immediately loaded from the database when an entity is loaded.

FetchType.EAGER: when an entity is loaded, the properties that define the emergency load are immediately loaded from the database.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report