In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces you how to configure mybatis in Spring boot, the content is very detailed, interested friends can refer to, hope to be helpful to you.
1 add related maven files
Org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-web org.mybatis.spring.boot mybatis-spring-boot-starter 1.1.1 mysql mysql-connector-java org. Springframework.boot spring-boot-devtools true
The complete pom package will not be posted here. Let's just look at the source code.
2. Application.properties add database and mybatis configuration
Mybatis.type-aliases-package=com.neo.entity / / package name of the corresponding entity class spring.datasource.driverClassName = com.mysql.jdbc.Driverspring.datasource.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8spring.datasource.username = rootspring.datasource.password = root
Springboot will automatically load spring.datasource.*-related configurations, the data source will be automatically injected into sqlSessionFactory, and sqlSessionFactory will be automatically injected into Mapper. By the way, you don't have to worry about everything, just pick it up and use it.
Add @ MapperScan to scan mapper packages in the startup class
@ SpringBootApplication@MapperScan ("com.neo.mapper") public class Application {public static void main (String [] args) {SpringApplication.run (Application.class, args);}}
Or add the annotation @ Mapper directly to the Mapper class. It is recommended to use the one above, otherwise it will be troublesome to add an annotation to each mapper.
3. Develop Mapper
The third step is the most critical piece. Sql production is all here.
Public interface UserMapper {@ Select ("SELECT * FROM users") @ Results ({@ Result (property = "userSex", column = "user_sex", javaType = UserSexEnum.class), @ Result (property = "nickName", column = "nick_name")}) List getAll () Select ("SELECT * FROM users WHERE id = # {id}") @ Results ({@ Result (property = "userSex", column = "user_sex", javaType = UserSexEnum.class), @ Result (property = "nickName", column = "nick_name")}) UserEntity getOne (Long id) @ Insert ("INSERT INTO users (userName,passWord,user_sex) VALUES (# {userName}, # {passWord}, # {userSex})") void insert (UserEntity user); @ Update ("UPDATE users SET userName=# {userName}, nick_name=# {nickName} WHERE id = # {id}") void update (UserEntity user); @ Delete ("DELETE FROM users WHERE id = # {id}") void delete (Long id);}
In order to get closer to production, I specially underlined user_sex and nick_name attributes in the database and inconsistent entity class attribute names. In addition, user_sex used enumerations
@ Select is the annotation of the query class, which is used by all queries
@ Result modifies the returned result set, and the associated entity class attribute corresponds to the database field one by one. If the entity class attribute and the database attribute name are the same, this attribute is not needed to decorate.
@ Insert is inserted into the database. Passing the entity class directly will automatically resolve the attribute to the corresponding value.
@ Update is responsible for the modification, or you can pass in the object directly.
@ delete is responsible for deletion
For more properties, please refer to here.
Note the difference between using the # symbol and the $symbol:
/ / This example creates a prepared statement, something like select * from teacher where name =?; @ Select ("Select * from teacher where name = # {name}") Teacher selectTeachForGivenName (@ Param ("name") String name); / / This example creates n inlined statement, something like select * from teacher where name = 'someName';@Select ("Select * from teacher where name =' ${name}'") Teacher selectTeachForGivenName (@ Param ("name") String name)
4. Use
The development of the relevant dao layer is basically completed in the above three steps, and you can use it as a normal class injection.
@ RunWith (SpringRunner.class) @ SpringBootTestpublic class UserMapperTest {@ Autowired private UserMapper UserMapper; @ Testpublic void testInsert () throws Exception {UserMapper.insert (new UserEntity ("aa", "a123456", UserSexEnum.MAN)); UserMapper.insert (new UserEntity ("bb", "b123456", UserSexEnum.WOMAN)); UserMapper.insert ("cc", "b123456", UserSexEnum.WOMAN)) Assert.assertEquals (3, UserMapper.getAll (). Size ());} @ Test public void testQuery () throws Exception {List users = UserMapper.getAll (); System.out.println (users.toString ());} @ Test public void testUpdate () throws Exception {UserEntity user = UserMapper.getOne (31); System.out.println (user.toString ()); user.setNickName ("neo") UserMapper.update (user); Assert.assertTrue (("neo" .equals (UserMapper.getOne (31). GetNickName ();}}
The controler layer in the source code has complete additions, deletions, modifications and queries, so it will not be posted here.
Minimalist xml version
The minimalist version of xml maintains the old tradition of mapping files. The optimization is mainly reflected in the implementation layer that does not need to implement dao. The system will automatically find the corresponding sql.1 and application.yml configurations in the mapping file according to the method name.
Which database does spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/ use? useUnicode=true&characterEncoding=utf-8 username: username password: password server: port: 8080 mybatis: config-location: classpath:config/mybatis-config.xml mapper-locations: classpath:mapper/*.xmlMyBatis configuration item interpretation: config-location: specify the location of the MyBatis main configuration file mapper-locations: specify the location of the mapper file. If your mapper files are placed by directory in the project, the corresponding configuration will be: mapper-locations: classpath:mapper/*/*.xml
At this point, assume that our resources structure looks like this:
| |-resources |-- config |-application.yml |-mybatis-config.xml |-- mapper |-CityMapper.xml |
3. Mybatis-config.xml configuration
There are different opinions on this configuration. I have one in it.
TypeAliases
. Students who do not understand can move to the document to see the relevant explanation.
You can also configure mapper here as many times as there are mapper. Of course, we have specified it in batch in application.yml, which is very convenient, so you don't have to write one by one here.
2. Add the mapping file of User
Id, userName,passWord,user_sex, nick_name SELECT FROM users SELECT FROM users WHERE id = # {id} INSERT INTO users (userName,passWord,user_sex) VALUES (# {userName}, # {passWord} # {userSex}) UPDATE users SET userName = # {userName}, passWord = # {passWord}, nick_name = # {nickName} WHERE id = # {id} DELETE FROM users WHERE id = # {id}
In fact, I moved the sql of mapper from the last version to the xml here.
3. Write the code of Dao layer
Public interface UserMapper {List getAll (); UserEntity getOne (Long id); void insert (UserEntity user); void update (UserEntity user); void delete (Long id);}
On how to configure mybatis in Spring boot to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.