当前位置:网站首页>JPA learning 2 - core annotation, annotation addition, deletion, modification and query, list query result return type, one to many, many to one, many to many
JPA learning 2 - core annotation, annotation addition, deletion, modification and query, list query result return type, one to many, many to one, many to many
2022-06-24 23:52:00 【Uh huh**】
List of articles
SpringDataJPA
summary
Spring A set of pairs provided JPA Operate on more advanced frameworks , Is in JPA A solution specifically designed for persistence under the specification

Core notes
Easy to use
Configure the of printing SQL Portability parameter
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--hibernate Yes JPA Standard support package -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.4.30.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.6.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!-- monitor sql journal == SQL You can carry parameters , If you use JPA Self contained SQL Printing does not carry parameters -->
<dependency>
<groupId>org.bgee.log4jdbc-log4j2</groupId>
<artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
<version>1.16</version>
</dependency>
</dependencies>
application.yml == Be careful mysql Driver name and database connection URL
server:
port: 8080
spring:
datasource:
username: root
password: root
# url: jdbc:mysql://localhost:3306/lrc_blog_test2?useSSL=false&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
url: jdbc:log4jdbc:mysql://localhost:3306/lrc_blog_test2?useSSL=false&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
# driver-class-name: com.mysql.cj.jdbc.Driver
driver-class-name: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
jpa:
show-sql: true
database-platform: org.hibernate.dialect.MySQL8Dialect
database: mysql
hibernate:
# ddl-auto: create
principle = JDK A dynamic proxy
@Repository Defined dao The interface will go through JDK The dynamic proxy is converted to SimpleJpaRepository Object to execute concrete CRUD operation
SimpleJpaRepository adopt EntityManager Object to execute concrete CRUD operation
and EntityManager The specific implementation is realized by Hibernate To perform JDBC operation
Simple code = Built in interface
application.yml
server:
port: 8080
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/lrc_blog_test?useSSL=false&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
show-sql: true
database-platform: org.hibernate.dialect.MySQLDialect
database: mysql
open-in-view: true
Book.java
@Getter
@Setter
@ToString
@Entity
@Table(name = "book")
public class Book implements Serializable {
private static final long serialVersionUID = 2095940921263481761L;
/** Primary key - Record insertion auto fill primary key processing {@path application.yml} */
@Id
@Column(name = "id")
private String id;
@Column(name = "create_time")
private String createTime;
@Column(name = "update_time")
private String updateTime;
/** Whether the record is deleted logically :0 Not delete 1 Logical deletion - Logical processing value definition {@path application.yml}*/
@Column(name = "is_del")
private Integer isDel;
/** Book status ;-1 Violations, 0 Published and made public 1 Published and private - Default 0 */
@Column(name = "status")
private String status;
/** Title */
@Column(name = "name")
private String name;
/** author */
@Column(name = "author")
private String author;
/** Nationality of the author */
@Column(name = "country")
private String country;
/** Download address */
@Column(name = "download_url")
private String downloadUrl;
/** file type */
@Column(name = "file_type")
private String fileType;
/** Reading experience */
@Column(name = "reading_feeling")
private String readingFeeling;
/** Book sharers - nickname */
@Column(name = "sharer")
private String sharer;
/** Whether the books violate the rules :0 No violation 1 Violations, - Violations cannot be displayed */
@Column(name = "is_violation")
private Integer isViolation;
// Book status
public final static String STATUS_VIOLATION = "-1";
public final static String STATUS_PUBLISH_PUBLIC = "0";
public final static String STATUS_PUBLISH_PRIVATE = "1";
}
BookDao.java
@Repository
public interface BookDao extends JpaRepository<Book, String> {
}
JPATest.java
@SpringBootTest
public class JPATest {
@Autowired
BookDao bookDao;
@Test
public void test1() {
List<Book> books = bookDao.findAll();
books.stream().forEach(System.out::println);
}
}
Customize SQL sentence
Inquire about
The way 1:dao Method name query form - Method name must findBy start
By method name ,JPA Automatic identification JPQL sentence 
SysUserDao.java
@Repository
public interface SysUserDao extends JpaRepository<SysUser, String> {
public SysUser findByIdAndNickName(String id, String nickName);
}
Test.java
@Test
public void test8() {
SysUser sysUser = sysUserDao.findByIdAndNickName("d32478155b6530951cf6b3da56848d5c", " Mm-hmm ");
System.out.println(sysUser);
}

The way 2:JPQL Query form
@Repository
public interface BookDao extends JpaRepository<Book, String>, JpaSpecificationExecutor<Book> {
//JPA Generate according to method name SQL
public List<Book> findByNameLike(String name);
// Write manually JPQL sentence The first parameter is zero :?1 The second parameter is :?2 And so on
@Query("from Book where name like ?1")
public List<Book> findByNamexxx(String name);
// Write manually JPQL sentence Use : Parameter name To fill in JPQL Parameters of
@Query("from Book where name like :name")
public List<Book> findByNamexxx2(String name);
}
test.java
@Test
public void test4() {
List<Book> books = bookDao.findByNameLike("% The brain %");
books.stream().forEach(System.out::println);
System.out.println("\n=========\n");
books = bookDao.findByNamexxx("% The brain %");
books.stream().forEach(System.out::println);
System.out.println("\n=========\n");
books = bookDao.findByNamexxx2("% The brain %");
books.stream().forEach(System.out::println);
}

The way 3:SQL Query form
BookDao.java
@Repository
public interface BookDao extends JpaRepository<Book, String>, JpaSpecificationExecutor<Book> {
@Query(value = "select * from book where name like :name ", nativeQuery = true)
public List<Book> findByNamexxx2(String name);
@Query(value = "select * from book where name like ?1 ", nativeQuery = true)
public List<Book> findByNamexxx3(String name);
}
BookDao.java
@Test
public void test5() {
List<Book> books = bookDao.findByNamexxx2("% The brain %");
books.stream().forEach(System.out::println);
}
@Test
public void test6() {
List<Book> books = bookDao.findByNamexxx3("% The brain %");
books.stream().forEach(System.out::println);
}
The way 4: Code level query , similar MyBatisPlus
BookDao.java
@Repository
public interface BookDao extends JpaRepository<Book, String>, JpaSpecificationExecutor<Book> {
}
Test.java
@Test
public void test9() {
List<SysUser> sysUsers = sysUserDao.findAll(new Specification<SysUser>() {
@Override
public Predicate toPredicate(Root<SysUser> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
Path<Object> nickName = root.get("nickName");
Path<Object> id = root.get("id");
Predicate predicate = criteriaBuilder.equal(nickName, " Mm-hmm ");
Predicate predicate2 = criteriaBuilder.equal(id, "d32478155b6530951cf6b3da56848d5c");
Predicate and = criteriaBuilder.and(predicate2, predicate);
return and;
}
});
sysUsers.forEach(System.out::println);
}

Test.java
@Test
public void test10() {
// Query criteria
Specification<SysUser> whereConditions = new Specification<SysUser>() {
@Override
public Predicate toPredicate(Root<SysUser> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
Path<Object> nickName = root.get("nickName");
Path<Object> id = root.get("id");
Predicate predicate = criteriaBuilder.like(nickName.as(String.class), "% Um. %");
Predicate predicate2 = criteriaBuilder.equal(id, "d32478155b6530951cf6b3da56848d5c");
return criteriaBuilder.or(predicate, predicate2);
}
};
// The sorting of records after query
Sort sort = Sort.by(Sort.Direction.DESC, "createTime", "id", "nickName");
List<SysUser> sysUsers = sysUserDao.findAll(whereConditions, sort);
sysUsers.forEach(System.out::println);
}

Test.java
@Test
public void test11() {
// Query criteria
Specification<SysUser> whereConditions = new Specification<SysUser>() {
@Override
public Predicate toPredicate(Root<SysUser> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
Path<Object> nickName = root.get("nickName");
Path<Object> id = root.get("id");
Predicate predicate = criteriaBuilder.like(nickName.as(String.class), "% Um. %");
Predicate predicate2 = criteriaBuilder.like(id.as(String.class), "%5%");
return criteriaBuilder.or(predicate, predicate2);
}
};
// The sorting of records after query
Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
// Paging information + Sort information
Pageable pageable = PageRequest.of(2, 2, sort);
Page<SysUser> page = sysUserDao.findAll(whereConditions, pageable);
List<SysUser> sysUsers = page.getContent();
sysUsers.forEach(System.out::println);
}

Three return types = Choose... According to your preference
BaseDB.java
@Getter
@Setter
@MappedSuperclass
public class BaseDB {
private static final long serialVersionUID = 3253505422347170166L;
/** Primary key - Record insertion auto fill primary key processing {@path application.yml} */
@Id
private String id;
@Column(name = "create_time")
private String createTime;
@Column(name = "update_time")
private String updateTime;
/** Whether the record is deleted logically :0 Not delete 1 Logical deletion - Logical processing value definition {@path application.yml}*/
@Column(name = "is_del")
private Integer isDel;
}
SysUser.java
@Getter
@Setter
@Entity
@Table(name = "sys_user")
public class SysUser extends BaseDB{
@Column(name = "nick_name")
String nickName;
@Column(name = "login_name")
String loginName;
@Override
public String toString() {
return "SysUser{" +
"id='" + getId() + '\'' +
", nickName='" + nickName + '\'' +
", loginName='" + loginName + '\'' +
'}';
}
}
SysUserDao.java
@Repository
public interface SysUserDao extends JpaRepository<SysUser, String> {
@Query(value = "select * from sys_user limit 5", nativeQuery = true)
public List<SysUser> getPage();
/** * @return Object[] It stores all column values of the data record */
@Query(value = "select * from sys_user limit 5", nativeQuery = true)
public List<Object[]> getPage2();
/** * @return org.springframework.data.jpa.repository.query.AbstractJpaQuery.TupleConverter.TupleBackedMap */
@Query(value = "select * from sys_user limit 5", nativeQuery = true)
public List<Map> getPage3();
}
Test.java
@Test
public void test3() {
System.out.println("\n============JavaBean form - recommend =========\n");
List<SysUser> sysUsers = sysUserDao.getPage();
sysUsers.forEach(System.out::println);
System.out.println("\n==========Object[] Pure column valued form - Not recommended ===========\n");
List<Object[]> sysUsers2 = sysUserDao.getPage2();
sysUsers2.stream()
.map(Arrays::toString)
.forEach(System.out::println);
System.out.println("\n==========Map form - recommend ===========\n");
List<Map> sysUsers3 = sysUserDao.getPage3();
sysUsers3.stream()
.map(HashMap::new)
.forEach(System.out::println);
}

modify 、 Delete
@Repository
@Transactional // Adding, deleting, or modifying requires adding transaction support
public interface BookDao extends JpaRepository<Book, String>, JpaSpecificationExecutor<Book> {
@Query("update Book set name = ?2 where id = ?1")
@Modifying //update Need to add this annotation
@Rollback(false) // Do not rollback after execution == If you add the first two annotations and cannot modify the data successfully , Then add this annotation
public void udpateBookName(String id, String name);
@Query("delete from Book where id = :id and name = :name")
@Modifying
@Rollback(false) // Do not rollback after execution == If you add the first two annotations and cannot modify the data successfully , Then add this annotation
public void deleteByIdName(String id, String name);
}
}
@Test
public void test5() {
bookDao.udpateBookName("0015ac644213f7db45d63e09c6403395", " test 2");
bookDao.deleteByIdName("0015ac644213f7db45d63e09c6403395", " test ");
}
Multi meter operation
One to many 、 For one more
SysUser.java
@Getter
@Setter
@Entity
@Table(name = "sys_user")
public class SysUser extends BaseDB implements Serializable {
@Column(name = "nick_name")
String nickName;
@Column(name = "login_name")
String loginName;
@OneToMany(targetEntity = ArticleComment.class,fetch = FetchType.EAGER)
@JoinColumn(name = "user_id", referencedColumnName = "id")
@NotFound(action= NotFoundAction.IGNORE)
List<ArticleComment> articleComments;
@Override
public String toString() {
return "SysUser{" +
"id='" + getId() + '\'' +
", nickName='" + nickName + '\'' +
", loginName='" + loginName + '\'' +
", createTime='" + getCreateTime() + '\'' +
'}';
}
}
ArticleComment.java
@Getter
@Setter
@Entity
@Table(name = "article_comment")
public class ArticleComment extends BaseDB implements Serializable {
/** Version number */
private static final long serialVersionUID = -6282048873013965389L;
@ManyToOne(targetEntity = SysUser.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name ="user_id", referencedColumnName = "id")
@NotFound(action= NotFoundAction.IGNORE)
private SysUser sysUser;
/** Comment on the article - article Tabular id - Logical foreign key associations */
@Column(name = "article_id")
private String articleId;
/** Parent comment id - article_comment Tabular id - Whether it is a sub comment , If it is empty, it is not a sub comment - Logical foreign key associations */
@Column(name = "parent_comment_id")
private String parentCommentId;
/** Commentator - user id - user Tabular id - Logical foreign key associations */
//@Column(name = "user_id")
//private String userId;
/** To whom is this comment addressed - user ID */
@Column(name = "replier_id")
private String replierId;
/** Comment content */
@Column(name = "comment_content")
private String commentContent;
/** The number of likes of the current comment */
@Column(name = "like_num")
private Integer likeNum;
/** Current reviews don't like counting */
@Column(name = "not_like_num")
private Integer notLikeNum;
@Override
public String toString() {
return "ArticleComment{" +
"id='" + getId() + '\'' +
", articleId='" + articleId + '\'' +
", parentCommentId='" + parentCommentId + '\'' +
", replierId='" + replierId + '\'' +
", commentContent='" + commentContent + '\'' +
", likeNum=" + likeNum +
", notLikeNum=" + notLikeNum +
'}';
}
}
SysUserDao.java
@Repository
public interface SysUserDao extends JpaRepository<SysUser, String>, JpaSpecificationExecutor<SysUser> {
@Query(value = "select * from sys_user limit 5", nativeQuery = true)
public List<SysUser> getPage();
/** * @return Object[] It stores all column values of the data record */
@Query(value = "select * from sys_user limit 5", nativeQuery = true)
public List<Object[]> getPage2();
/** * @return org.springframework.data.jpa.repository.query.AbstractJpaQuery.TupleConverter.TupleBackedMap */
@Query(value = "select * from sys_user limit 5", nativeQuery = true)
public List<Map> getPage3();
public SysUser findByIdAndNickName(String id, String nickName);
}
ArticleCommentDao.java
@Repository
public interface ArticleCommentDao extends JpaRepository<ArticleComment, String>, JpaSpecificationExecutor<ArticleComment> {
}
Inquire about
@Test
@Transactional // Lazy loading , Could not find exception for agent , If you load it immediately, you can not add
public void test13() {
List<SysUser> sysUsers = sysUserDao.getPage();
sysUsers.forEach(sysUser -> {
List<ArticleComment> articleComments = sysUser.getArticleComments();
System.out.println(articleComments.size() + ":" + articleComments);
});
}

@Test
@Rollback(value = false)
@Transactional
public void test16() {
ArticleComment articleComment = articleCommentDao.getOne("1346e1060e95de36d8d8a7bbc8925dfb");
SysUser sysUser = articleComment.getSysUser();
System.out.println(sysUser);
}

Insert
The main table already contains foreign key records
Test.java
@Test
public void test12() {
SysUser sysUser = sysUserDao.findById("c08d391e02bc11eb9416b42e99ea3e69").get();
ArticleComment articleComment = new ArticleComment();
articleComment.setId(UUID.fastUUID().toString(true));
articleComment.setCommentContent("test==articleComment");
articleComment.setSysUser(sysUser);
articleCommentDao.save(articleComment);
}
The main table does not contain foreign key records
@Test
@Rollback(value = false)
@Transactional
public void test15() {
SysUser sysUser = new SysUser();
sysUser.setId(UUID.fastUUID().toString(true));
sysUser.setNickName(String.valueOf(" love you test"));
ArticleComment articleComment = new ArticleComment();
articleComment.setId(UUID.fastUUID().toString(true));
articleComment.setSysUser(sysUser);
articleComment.setCommentContent(String.valueOf("test==articleComment"));
sysUserDao.save(sysUser);
articleCommentDao.save(articleComment);
}
Many to many
Inquire about
Role.java
@Getter
@Setter
@Entity
@Table(name = "role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id2;
@Column(name = "role_name")
String roleName;
@ManyToMany(targetEntity = User.class, fetch = FetchType.EAGER)
@JoinTable(name = "user_role_rel",
// The relationship between the current table and the intermediate table
joinColumns = {
@JoinColumn(name = "role_id", referencedColumnName = "id2")},
// The relationship between another table and the intermediate table
inverseJoinColumns = {
@JoinColumn(name = "user_id", referencedColumnName = "id1")})
List<User> roles;
}
User.java
@Getter
@Setter
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id1;
@Column(name = "user_name")
String userName;
@ManyToMany(targetEntity = Role.class, fetch = FetchType.EAGER)
@JoinTable(name = "user_role_rel",
// The relationship between the current table and the intermediate table
joinColumns = {
@JoinColumn(name = "user_id", referencedColumnName = "id1")},
// The relationship between another table and the intermediate table
inverseJoinColumns = {
@JoinColumn(name = "role_id", referencedColumnName = "id2")})
List<Role> roles;
}
Test.java
@Test
@Rollback(value = false)
@Transactional
public void test17() {
User user = new User();
user.setUserName("lrc2");
Role role = new Role();
role.setRoleName(" tourists 2");
// Intermediate table relationship maintenance == If the data without an intermediate table is empty
role.setRoles(Arrays.asList(user));
userDao.save(user);
roleDao.save(role);
}

边栏推荐
- First person singular reading notes
- Start QT program
- 当初吃土建起来的“中台”,现在为啥不香了?
- VR全景制作的优势是什么?为什么能得到青睐?
- Yyds dry goods inventory tells us 16 common usage scenarios of redis at one go
- Helix distance of point
- 美国众议院议员:数字美元将支持美元作为全球储备货币
- Hibernate学习2 - 懒加载(延迟加载)、动态SQL参数、缓存
- Hello C (IV) -- pointer and function
- Using external Libpcap library on ARM platform
猜你喜欢

svg+js键盘控制路径

Yyds dry goods counting uses xshell to implement agent function

SAP PA certificate for no birds, which can be tested by new peers

How to use stm32subeide SWV function

Continuous soul torture from two MySQL indexes of interviewers

What are the advantages of VR panoramic production? Why is it favored?

Phprunner 10.7.0 PHP code generator

ArcGIS loads free online historical images as the base map (no plug-ins are required)

VR全景制作的优势是什么?为什么能得到青睐?

JPA学习2 - 核心注解、注解进行增删改查、List查询结果返回类型、一对多、多对一、多对多
随机推荐
如何化解35岁危机?华为云数据库首席架构师20年技术经验分享
One way 和two way ANOVA分析的区别是啥,以及如何使用SPSS或者prism进行统计分析
VR全景制作的优势是什么?为什么能得到青睐?
Global and Chinese 3-Chlorobenzaldehyde industry operation mode and future development trend report 2022 ~ 2028
Andersen Global借助巴勒斯坦成员公司加强中东平台
节奏快?压力大?VR全景客栈带你体验安逸生活
Hyperledger Fabric 2. X dynamic update smart contract
Investment analysis and prospect forecast report of global and Chinese octadecyl cyclopentanoate industry from 2022 to 2028
Morris遍曆
Helix distance of point
ArcGIS loads free online historical images as the base map (no plug-ins are required)
JPA学习1 - 概述、JPA、JPA核心注解、JPA核心对象
第三代电力电子半导体:SiC MOSFET学习笔记(五)驱动电源调研
js监听页面或元素scroll事件,滚动到底部或顶部
Use of types, values, namespaces, combinations, etc. in typescript
Record a Webflux application memory leak troubleshooting
Tutorial details | how to edit and set the navigation function in the coolman system?
7-5 maximal submatrix sum problem
Start QT program
为什么越来越多的实体商铺用VR全景?优势有哪些?