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 to deal with Jpa quickly

2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

The main content of this article is "how to fix Jpa quickly". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to fix Jpa quickly".

Data preparation

The data tables used by the database are designed as follows

The statement of the table is as follows

SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0;-- Table structure for t_user-DROP TABLE IF EXISTS `t _ user` CREATE TABLE `t _ user` (`id` int (11) NOT NULL AUTO_INCREMENT, `user_ name` varchar (255) DEFAULT NULL, `password` varchar (255) DEFAULT NULL, `last_login_ time` datetime DEFAULT NULL, `sex` tinyint (4) DEFAULT NULL, PRIMARY KEY (`id`) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=armscii8 -- Records of t_user-BEGIN; INSERT INTO `t _ user` VALUES (1, 'json',' 123, '2019-07-27 16 purl 01VR 21, 1) INSERT INTO `t _ user`VALUES (2, 'jack jo',' 123, '2019-07-24 16 jack jo', 01jack jo', 37, 1); INSERT INTO `tuser`User`User` VALUES (3,' manistal', '123, 1); INSERT INTO `tuser`User` VALUES (4,' landengdeng', '123,' 2019-07-24 16 purge 01jack jo', 37, 1) INSERT INTO `t _ user` VALUES (5, 'max',' 123, '2019-07-24 16 max', 01max', 37); COMMIT; SET FOREIGN_KEY_CHECKS = 1

New Spring Boot project

Select File-> New-> Project, select Spring Initializr, select next, fill in the package name and project name, and select next. Select dependency, tick before Spring web starter, and sql option is any Spring Data Jpa,MySql project name.

Introduction of Pom configuration

Org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-webflux mysql mysql-connector-java runtime org.springframework.boot spring-boot-starter-test Test io.projectreactor reactor-test test

Write configuration file application.yml

Server: port: 8086 spring: # General data source configuration datasource: driverClassName: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/demo_test?useSSL=false&useUnicode=true&characterEncoding=utf8 username: root password: 123 jpa: # this parameter is used when the table is created Switch the default storage engine to the database-platform: org.hibernate.dialect.MySQL5InnoDBDialect # configuration for InnoDB to print out the executed SQL statement information in the log. Show-sql: true hibernate: # configuration indicates that the table ddl-auto: create corresponding to the entity class should be deleted and created when the program starts

Write sample code

Create a new entity object UserDao.java

Entity classes need to be annotated using @ Entity annotation, attributes of entity classes need to be annotated, and @ Id annotation components are used to label non-primary keys using @ Column

/ * user entity class * * / @ Entity @ Table (name= "t_user") public class UserDO {@ Id private Integer id; @ Column (name= "user_name", length = 200) private String userName; @ Column (name= "password", length = 200) private String password; @ Column (name= "sex") private Integer sex; @ Column (name= "last_login_time") private Date lastLoginTime Public Integer getId () {return id;} public void setId (Integer id) {this.id = id;} public String getUserName () {return userName;} public void setUserName (String userName) {this.userName = userName;} public String getPassword () {return password } public void setPassword (String password) {this.password = password;} public Integer getSex () {return sex;} public void setSex (Integer sex) {this.sex = sex;} public Date getLastLoginTime () {return lastLoginTime;} public void setLastLoginTime (Date lastLoginTime) {this.lastLoginTime = lastLoginTime;}}

Create a new warehouse interface class UserRepository

Warehouse interface class, UserRepository is our commonly used Dao interface, we need to pay attention to

Use @ Repository annotations

Inherit JPARepository

UserRepository does not need to write any code to add, delete, check and modify.

@ Repository public interface UserRepository extends JPARepository {}

Write test cases

In

Src/test/java/com/fishpro/jpa/

Next, a new addition

UserRepositoryTest.java

Use

@ RunWith (SpringRunner.class)

And

@ SpringBootTest

Annotate annotation class.

@ RunWith (SpringRunner.class) @ SpringBootTest public class UserRepositoryTest {}

Add new user data

/ * initialize an object UserDO test Insert process * * / @ Before public void before () {UserDO userDO=new UserDO (); userDO.setId (1); userDO.setUserName ("fishpro"); userDO.setSex (1); userDO.setLastLoginTime (new Date ()); userDO.setPassword ("passWord"); userRepository.save (userDO);}

Query individual user data

@ Test public void testFind () {Optional optionalUserDO=userRepository.findById (1); if (optionalUserDO.isPresent ()) {UserDO userDO=optionalUserDO.get (); System.out.println ("testFind user" + userDO.getUserName ());}}

Query multiple data

@ Test public void testFindAll () {List list=userRepository.findAll (); for (UserDO user:list) {System.out.println ("user_name:" + user.getUserName ());}}

Update data

Test public void testUpdate () {Optional optionalUserDO=userRepository.findById (1); if (optionalUserDO.isPresent ()) {UserDO userDO=optionalUserDO.get (); userDO.setUserName ("fishpro001"); userRepository.save (userDO); System.out.println ("testFind user" + userDO.getUserName ());}}

Delete data

@ After public void after () {userRepository.deleteById (1); userRepository.deleteById (2); userRepository.deleteById (3);}

Joint primary key

For example, if you define that userId,roleId is the primary key in the table, set it this way.

1. Define a primary key class

Public class UserRoleKey implements Serializable {private Integer userId; private Integer roleId;}

two。 Define entity classes

@ Entity @ Table (name= "t_user_role") @ IdClass (UserRoleKey.class) / / Note that the defined primary key class public class UserRoleDO {@ Id private Integer userId; @ Id private Integer roleId; public Integer getUserId () {return userId;} public void setUserId (Integer userId) {this.userId = userId;} public Integer getRoleId () {return roleId is introduced here. } public void setRoleId (Integer roleId) {this.roleId = roleId;}} so far, I believe you have a deeper understanding of "how to get Jpa done quickly". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue 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: 282

*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