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

Example Analysis of entity Class Alias, Multi-parameter and dynamic SQL in Mybatis

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces the Mybatis entity class aliases, multi-parameters, dynamic SQL example analysis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian with you to understand.

I. explanation

Start by talking about entity class aliases, multi-parameters, dynamic SQL, etc.

Second, start the database table DROP TABLE IF EXISTS `test` CREATE TABLE `test` (`id` bigint (20) NOT NULL AUTO_INCREMENT, `name` varchar (200) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `salary` decimal (10,2) NOT NULL, `age`int (11) NULL DEFAULT NULL, `city`varchar (255,255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `job` varchar (255CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL) ENGINE = InnoDB AUTO_INCREMENT = 43 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic -Records of test---INSERT INTO `test` VALUES (1, 'Xiaoming', 40000.00, 18, 'Beijing', 'programmer') INSERT INTO `test`VALUES (2, 'Xiaoqiang', 50000.00, 19, 'Nanjing', 'Program Wang'); INSERT INTO `test` VALUES (3, 'Xiaoyue', 50000.00, 20, 'Tianjin', 'Program Dog'); INSERT INTO `test`VALUES (4, 'Xiaoyue Bird', 40000.00, 21, 'Guangzhou', 'Program loser'); 2.1 entity category 2.1.1 method 1. Create the entity class package entity;import java.math.BigDecimal;/** * @ author and find out more about the official account: Muzi's round-the-clock programming * A programmer who lives at the bottom of the Internet and is doing additions, deletions, changes and searches, unworldly artifacts * @ create 2021-08-25 22:05 * / public class TestEntity {private Long id; private String name; private BigDecimal salary; private Integer age; private String city; private String job / / get set method omits IntelliJ IDEA generation shortcut is Alt+Inert chooses Getter and Setter / / toString method omits IntelliJ IDEA generation shortcut is Alt+Inert chooses toString} 2. Create XML

Mybatis-config.xml

The order of configuration files should be configured as follows:

.. 3. Use the alias select * from test where id = # {id} public class TestMain {public static void main (String [] args) throws Exception {String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream (resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder () .build (inputStream) Try (SqlSession session = sqlSessionFactory.openSession ()) {/ / get Mapper through sesson this Mapper can program Mybatis's agent Mapper TestMapper mapper = session.getMapper (TestMapper.class); System.out.println (mapper); / / query data TestEntity testEntity = mapper.get (1L); System.out.println (testEntity) 2.1.2 the second way

Scan packet path mybatis-config.xml

By scanning the package path, the entity class name defaults to the lowercase of the java class.

For example: TestEntity-- > testEntity

You can also annotate and specify:

@ Alias ("testEntityxxoo") public class TestEntity {/ / other ellipsis}

If you write the note @ Alias, the alias is not "testEntity", but "testEntityxxoo".

2.1.3 mybatis default alias

Mapping type _ bytebyte_longlong_shortshort_intint_integerint_doubledouble_floatfloat_booleanbooleanstringStringbyteBytelongLongshortShortintIntegerintegerIntegerdoubleDoublefloatFloatbooleanBooleandateDatedecimalBigDecimalbigdecimalBigDecimalobjectObjectmapMaphashmapHashMaplistListarraylistArrayListcollectionCollectioniteratorIterator2.2 insert data returns INSERT INTO `test` (`name`, `salary`) VALUE (# {name}, # {salary}); public class TestMain {public static void main (String [] args) throws Exception {String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream (resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder (). Build (inputStream) Try (SqlSession session = sqlSessionFactory.openSession ()) {/ / get Mapper through sesson this Mapper can program Mybatis's agent Mapper TestMapper mapper = session.getMapper (TestMapper.class); / / Test whether id is in the entity class TestEntity testEntity = new TestEntity (); testEntity.setName ("duckling"); testEntity.setSalary (new BigDecimal (100000)) Mapper.save (testEntity); System.out.println ("Primary key:" + testEntity.getId ());}

Output result:

The primary key is not returned directly, but the primary key value is set to the inserted object

2.2.2 Mode 2 SELECT LAST_INSERT_ID () INSERT INTO `test` (`id`, `name`, `salary`) VALUE (# {id}, # {name}, # {salary}) 2.3 multiple parameters 2.3.1 one parameter / / query TestEntity get (Long id) according to the primary key Select * from test where id = # {id} select * from test where id = # {xx} select * from test where id = # {oo} select * from test where id = # {aaabbb}

If there is only one parameter, and the parameter type is Java base type or String type, when using this parameter

# {xxoo} xxoo can be any character independent of the method input parameter name

In the above example: id, xx, oo, aaabbb can all be used, but ha, we generally know the meaning of the name, what parameters we pass (id), we xml use # {passed parameters} this is not necessary, but we can follow this specification.

2.3.2 entity class with multiple parameters / / add void save (TestEntity testEntity); INSERT INTO `test` (`name`, `salary`) VALUE (# {name}, # {salary})

This is easy to understand. What the entity class parameters are called is used in # {}.

2.3.3 @ Param comments for multiple parameters / / Fuzzy query List listByNameAndAge (@ Param ("name") String name,@Param ("age") Integer age based on name Select * from test where 1 and name like CONCAT ('%', # {name},'%') and age = # {age} public class TestMain {public static void main (String [] args) throws Exception {String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream (resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder (). Build (inputStream) Try (SqlSession session = sqlSessionFactory.openSession ()) {/ / get Mapper through sesson this Mapper can program Mybatis's agent Mapper TestMapper mapper = session.getMapper (TestMapper.class); List list = mapper.listByNameAndAge ("Xiaoqiang", 19); System.out.println (list);}} 2.3.4 Map with more than one parameter

Using Map is almost the same as using an entity class. The key value can be regarded as the field name of the entity class.

/ / pass List listByNameAndAgeMap (Map param) in multi-parameter Map mode; select * from test where 1 and name like CONCAT ('%', # {name},'%') and age = # {age} public class TestMain {public static void main (String [] args) throws Exception {String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream (resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder () .build (inputStream) Try (SqlSession session = sqlSessionFactory.openSession ()) {/ / get Mapper through sesson this Mapper can program Mybatis agent Mapper TestMapper mapper = session.getMapper (TestMapper.class); Map param = new HashMap (); param.put ("name", "Xiaoqiang"); param.put ("age", 19); List list = mapper.listByNameAndAgeMap (param) Default of more than 2.3.5 parameters for System.out.println (list);}

There are two sets of parameters by default:

Arg0, arg1, arg2, argxxx; arg starts from 0 according to the order of method parameters

Param1, param2, param3, paramxxx; param starts from 1 in the order of method parameters

/ / nothing is needed for List listByNameAndAgeNone (String name, int age) Select * from test where 1room1 and name like CONCAT ('%', # {arg0},'%') and age = # {arg1} select * from test where 1room1 and name like CONCAT ('%', # {param1},'%') and age = # {param2} public class TestMain {public static void main (String [] args) throws Exception {String resource = "mybatis-config.xml" InputStream inputStream = Resources.getResourceAsStream (resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder (). Build (inputStream); try (SqlSession session = sqlSessionFactory.openSession ()) {/ / get Mapper through sesson Mapper TestMapper mapper = session.getMapper (TestMapper.class); List list = mapper.listByNameAndAgeNone ("Xiaoyue", 20); System.out.println (list) The basic value of 2.3.6 array parameters & entity class

Note that if the array is passed, the default parameter name is arry

1. Query data based on multiple ages: / / query List listByAges (int [] ages) by age set; select * from test where 1 query 1 and age in # {age} public class TestMain {public static void main (String [] args) throws Exception {String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream (resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder (). Build (inputStream) Try (SqlSession session = sqlSessionFactory.openSession ()) {/ / get Mapper through sesson this Mapper can program Mybatis proxy Mapper TestMapper mapper = session.getMapper (TestMapper.class); int [] ages = new int [] {19pr 20}; List list = mapper.listByAges (ages); System.out.println (list);}} 2. Multi-conditional query by name and age

For example, the name is Xiaoqiang and the age is 19 or the name is Xiaoyue age is 20

/ / query List listByNameAndAges (TestEntity [] params) based on multiple sets of parameters; select * from test where 1 query 1 and ((name = # {item.name} and age = # {item.age})) public class TestMain {public static void main (String [] args) throws Exception {String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream (resource) SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder (). Build (inputStream); try (SqlSession session = sqlSessionFactory.openSession ()) {/ / get Mapper through sesson this Mapper programming agent Mapper TestMapper mapper = session.getMapper (TestMapper.class); TestEntity [] params = new TestEntity [2]; TestEntity testEntity01 = new TestEntity (); testEntity01.setName ("Xiaoqiang") TestEntity01.setAge (19); TestEntity testEntity02 = new TestEntity (); testEntity02.setName ("Xiaoyue"); testEntity02.setAge (20); params [0] = testEntity01; params [1] = testEntity02; List list = mapper.listByNameAndAges (params); System.out.println (list);}

The sql format of the final output is as follows:

Select* from test where 1 # 1 and (

(name = 'Xiaoqiang' and age = 19) or

(name = 'Little month' and age = 20)

)

2.3.7 the basic value of set parameters & entity class

Sets are similar to arrays, but there are still some differences

Difference 1: if the collection does not specify a parameter name, it defaults to: collection or list is not array.

Difference 2: size (), not length, is used to determine the size of the collection.

2.4 description of the four labels

Select is one of the most frequently used tags in Mybatis. Unlike insert update delete, it doesn't change the database value, it just checks

Insert, update and delete will change the values of the database. These three tags can be mixed, that is, they have the same function. The meaning of the three tags is to distinguish between adding, modifying and deleting in business. Generally speaking, we also follow this use.

Thank you for reading this article carefully. I hope the article "sample Analysis of entity Class aliases, Multi-parameters and dynamic SQL in Mybatis" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

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