Database access middleware--basic use of springdata-jpa

2. Single table SQL operation-using keyword patchwork method

review

public interface UserRepository extends JpaRepository<User,Integer> {
    
    
    User findByUsernameLike(String username);
}

		@GetMapping("/user/username/{username}")
    public Object findUserByUsername(@PathVariable String username){
    
    
        return userRepository.findByUsernameLike("%"+username+"%");
    }

1. Single table sql operation—method of using keywords to piece together

Keywords Example JPQL fragment
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2
Is,Equals findByFirstnameIs,findByFirstnameEquals … where x.firstname = ?1
Between findByStartDateBetween … where x.startDate between ?1 and ?2
LessThan findByAgeLessThan … where x.age < ?1
LessThanEqual findByAgeLessThanEqual … where x.age ⇐ ?1
GreaterThan findByAgeGreaterThan … where x.age > ?1
GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1
After findByStartDateAfter … where x.startDate > ?1
Before findByStartDateBefore … where x.startDate < ?1
IsNull findByAgeIsNull … where x.age is null
IsNotNull,NotNull findByAge(Is)NotNull … where x.age not null
Like findByFirstnameLike … where x.firstname like ?1
NotLike findByFirstnameNotLike … where x.firstname not like ?1
StartingWith findByFirstnameStartingWith … where x.firstname like ?1 (parameter bound with appended %)
EndingWith findByFirstnameEndingWith … where x.firstname like ?1 (parameter bound with prepended %)
Containing findByFirstnameContaining … where x.firstname like ?1 (parameter bound wrapped in %)
OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc
Not findByLastnameNot … where x.lastname <> ?1
In findByAgeIn(Collection ages) … where x.age in ?1
swimming findByAgeNotIn(Collection age) … where x.age not in ?1
TRUE findByActiveTrue() … where x.active = true
FALSE findByActiveFalse() … where x.active = false
IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstame) = UPPER(?1)

2. Single table sql operation - case of using keywords to piece together methods

2.1. Related query questions

● Search for people who are 22 years old or younger;
● Search for people who are 20-22 years old and their gender is male;
● Search for people who are married and their gender is male;

2.2. Table structure

Person
pid varchar(32)
pname varchar(255) unique
psex varchar(255)
page int(3)
getmarried boolean

2.3. Precautions

  1. Do not include isXxx or getXxx names in entity class attribute names, which will lead to keyword assembly errors.
  2. As long as there are capital letters in the middle of the entity class attribute name, the database field name will be separated by underscores. For example, if you
    use isMarried attribute name, then the entity class field name will become is_married, which will easily lead to the failure. value
  3. The attribute name type is boolean and will become bit(1) in some databases, where 0 is false and 1 is true.

src/main/resources/application.properties

#mysql的配置信息
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#支持SQL 输出
spring.jpa.show-sql=true
#format 一下 SQL 进行输出
spring.jpa.properties.hibernate.format_sql=true
#自动生成开启,让表数据会自动跟随entity类的变化而变化
#spring.jpa.properties.hibernate.hbm2ddl.auto=update
#开启自动更新,若数据库没有对应的表,则生成,若有,则检查是否需要更改
spring.jpa.hibernate.ddl-auto=update

src/main/java/com/study/springdatajpademosecond/entity/Person.java

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;


@Data//geter、setter、equals、hashcode以及tostring
@Entity
@AllArgsConstructor//全参构造
@NoArgsConstructor//无参构造
@Builder// 部分参数构造
public class Person {
    
    
    @Id
    @GenericGenerator(name = "myuuid",strategy = "uuid")
    @GeneratedValue(generator = "myuuid")
    private String pid;
    @Column(unique = true)
    private String pname;
    @Column
    private String psex;
    @Column
    private Integer page;
    @Column
    private boolean getmarried;
}

src/main/java/com/study/springdatajpademosecond/entity/PersonInfo.java

public interface PersonInfo {
    
    
    String getPid();
    String getPname();
    String getPsex();
    String getPage();
    String getGetmerried();
    Integer getBid();
    String getBname();
    double getBprice();
}

src/main/java/com/study/springdatajpademosecond/repository/PersonRepository.java

import com.study.springdatajpademosecond.entity.Person;
import com.study.springdatajpademosecond.entity.PersonInfo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;


public interface PersonRepository extends JpaRepository<Person,String> {
    
    
    //1、查询出年龄小于等于22岁的人;
    List<Person> findAllByPageIsLessThanEqual(Integer age);
    //2、查询出年龄在20-22岁之间并且性别是男的人
    List<Person> findAllByPageBetweenAndPsexEquals(Integer lowage,Integer highage,String sex);
    //3、查询出已经结婚并且性别是男的人
    List<Person> findAllByGetmarriedIsTrueAndPsexEquals(String psex);

}


2.3. Testing

@SpringBootTest
class SpringdataJpaDemoSecondApplicationTests {
    
    
    @Resource
    private PersonRepository personRepository;
     @Test
    void contextLoads() {
    
    
      //初始化表
      //  initPersons();
      //1、查询出年龄小于等于22岁的人;
      System.out.println(personRepository.findAllByPageIsLessThanEqual(22));
      System.out.println("---------------------------------------------------");
        //2、查询出年龄在20-22岁之间并且性别是男的人
      System.out.println(personRepository.findAllByPageBetweenAndPsexEquals(20,22,"男"));
      System.out.println("---------------------------------------------------");
        //3、查询出已经结婚并且性别是男的人
       System.out.println(personRepository.findAllByGetmarriedIsTrueAndPsexEquals("男"));
    }
   // 初始化数据库 加入
   private void initPersons() {
    
    
        List<Person> list = new ArrayList<>();
        Collections.addAll(list,
                Person.builder().pname("zhangsan").psex("男").page(22).getmarried(false).build(),
                Person.builder().pname("lisi").psex("女").page(21).getmarried(true).build(),
                Person.builder().pname("wangwu").psex("男").page(20).getmarried(false).build(),
                Person.builder().pname("zhaoliu").psex("女").page(23).getmarried(true).build(),
                Person.builder().pname("sunqi").psex("男").page(25).getmarried(true).build());
        personRepository.saveAll(list);
    }
}

3. Single-table SQL operations-problems and solutions that cannot be solved using keyword patching methods

1. Causes

  • The attribute name of the entity class cannot be mapped to the field name of the table, resulting in the keyword not being found.
  • The CRUD operation method is more alternative or you don’t want to use keywords.
  • Involves multi-table operations

2. Solution

2.1. Use sql statements to write sql

2.2. Use hql statement to write sql

See the documentation for details

3. Demonstrate the use of sql statements to write sql

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-50bas3S1-1690894364157) (Basic use of 005-springdata-jpa.assets/image-20211020211827823.png)]

3.1. Implement interface

public interface PersonRepository extends JpaRepository<Person,String> {
    
    

    //4、根据pname来模糊删除一个person数据
    @Transactional
    @Modifying
    @Query(value = "delete from Person where pname like %:pname%")
    void deleteByName(@Param("pname") String pname);
    //5、使用HQL或者是sql来书写一个查询语句,查询出年龄在20-22岁,性别是女的人
//    @Query(value = "select * from person where page between 20 and 22 and psex='女'",nativeQuery = true)
    @Query(value = "select p from Person p where p.page between 20 and 22 and p.psex='女'")
    List<Person> findPerson();
    //6、使用SPEL表达式来完成person表的修改操作
    @Modifying
    @Transactional
    @Query(value = "update person set pname=:#{#person.pname},psex=:#{#person.psex},page=:#{#person.page} " +
            "where pid=:#{#person.pid}",nativeQuery = true)
    void updatePerson(@Param("person") Person person);
}

3.2. Testing

    private void createSqlTest() {
    
    
        //        personRepository.deleteByName("si");
//        System.out.println(personRepository.findPerson());
        personRepository.updatePerson(Person.builder().pid("402882f870e8a2cd0170e8a2d6470002").
                pname("刘德华").psex("男").page(60).build());
    }

4. Spring data jpa reverse engineering and multi-table query

1. Three forms

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-oNxZg4oN-1690894364158) (Basic use of 005-springdata-jpa.assets/image-20211217162055532.png)]

VO does not explain

2. Spring data jpa reverse operation

2.1. Related database

Right side of idea—database—±–data source—HSQLDB

url environment jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true

then test

2.2. Reverse generation

Project structure on the right side of idea—project settigs----Modules—JPA—±-select the default

persistence on the left side of idea —

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-tQGJpKQp-1690894364158) (Basic use of 005-springdata-jpa.assets/image-20211218190056822.png)]

Select entity package

Then select book reverse generation

At this time, the entity class can be generated

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-lU08ARRp-1690894364158) (Basic use of 005-springdata-jpa.assets/image-20211218190413016.png)]

3. Multi-table query

3.1. Joint table query-check the owner of the book based on the book title

 //7、联表查询-根据书名来查该书籍的拥有者
    @Query(value = "select p from Person p inner join Book b on p.pid=b.pid where b.bname=:bname")
    Person findPersonByBname(@Param("bname") String bname);


     //测试 7、联表查询-根据书名来查该书籍的拥有者
     System.out.println(personRepository.findPersonByBname("三国演义"));


3.2. Joint table query - joint table query - query person and book based on user ID

3.2.1. Create interface form

1. Create an interface

PersonInfo is created to display the parts of person and book that need to be displayed

public interface PersonInfo {
    
    
    String getPid();
    String getPname();
    String getPsex();
    String getPage();
    String getGetmerried();
    Integer getBid();
    String getBname();
    double getBprice();
}

2. Specific inquiries

    @Query(value = "select p.pid as pid,p.pname as pname,p.psex as psex,p.getmarried as getmarried," +
            "b.bid as bid,b.bname as bname,b.bprice as bprice from Person p inner join Book b on p.pid=b.pid " +
            "where p.pid=:pid")
    List<PersonInfo> findAllInfo(@Param("pid") String pid);

Be sure to use aliases

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-Vj3fFBij-1690894364159) (Basic use of 005-springdata-jpa.assets/image-20211218191630339.png)]

List<PersonInfo> allInfo = personRepository.findAllInfo("402882f870e8a2cd0170e8a2d6470002");
        for (PersonInfo info:allInfo
             ) {
    
    
            System.out.println(info.getPid()+","+info.getPname()+","+info.getPsex()+","+info.getPage()+","+info.getGetmarried()+","+
                    info.getBid()+","+info.getBname()+","+info.getBprice());
        }

3.2.2. Through collection form

 //使用集合来接收数据-List<Map<>>     System.out.println(personRepository.findAllInfo2("402882f870e8a2cd0170e8a2d6470002"));
    //通过集合来接收数据-list
   List<Object> allInfo1 = personRepository.findAllInfo1("402882f870e8a2cd0170e8a2d6470002");
        Object[] o = (Object[])allInfo1.get(0);
        System.out.println(Arrays.toString(o));

5. Query-DSL

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_39213232/article/details/132050645