Let’s talk briefly about JPA and SpringDataJPA

1.What is JPA?

The full name of JPA is the abbreviation of Java Persistence API. The Chinese name is: java persistence layer API. It is the mapping relationship between JDK5.0 annotations or XML description objects and relational tables, and persists the test object of the runner into the database. It can be understood as , java code operation object, to realize the brief operation of the database.

When it comes to mapping, or object-relational tables, then we can talk about ORM.

So what is ORM?

The full name of ORM is Object Relational Mapping. The Chinese name is Object Relational Mapping. Like JPA, it also operates the database through operating objects because JPA is encapsulated based on ORM.

Common ORM frameworks include: Hiberate TopLink OpenJPA

It may be a bit abstract. For example, as we all know, there are many database drivers, the most famous ones are MySQL and Oracle. When we usually write code, we often talk about JDBC. Yes, when we operate the database, we usually call it through JDBC. It is operated by drivers, that is to say, JDBC can be understood as the top of the food chain.

JPA has also jumped to the top of another food chain through the ORM framework.

2.What are the commonly used annotations in JPA?

We can take a look at the code of the entity class

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity //Mark entity class
@Table(name = "user") //Associated table
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column
    private Integer id;
    @Column
    private String username;
    @Column
    private String birthday;
    @Column
    private String sex;
    @Column
    private String address;
}

The three annotations above are lombok annotations:

@Data is the getter and setter methods,
@AllArgsConstructor is a parameterized constructor
@NoArgsConstructor is a parameterless constructor
@Entity specifies that it is an instance class
@Column describes the corresponding relationship between the attribute and the database field. If the field and attribute names are the same, they can be omitted
@Table(name = "user") specifies that the table name we operate is the user table
@Id specifies that the current field is the primary key id

@GeneratedValue(strategy = GenerationType.IDETITY) specifies the current primary key id to be incremented (the choice here does not necessarily have to be incremented, strategy has four attributes to choose from)
public enum GenerationType {
    TABLE,
    SEQUENCE,
    IDENTITY,
    AUTO;

    private GenerationType() {
    }
}

3.JPA core configuration file

It is said that each framework has its own configuration file, and JPA is no exception. Its location is under the resources folder under src under the java project. Create a MATA-INF folder under this folder. Create a configuration file named persistence.xml.

You can guess half of it in the file, whether you must configure the database. Otherwise, if there is no driver or address, where can I find this data sheet?

There are a lot of them available online, so I won’t go into the configuration file code here.

4.Basic operations of CRUD

This is the code that will be executed every time it is added, deleted, modified, and checked. I extracted it here. You can understand that the meaning here is

Connect to the database and start the transaction before operating

After the action method, commit the transaction and close the resource.

 private EntityManagerFactory factory=null;
    private EntityManager manager=null;
    private EntityTransaction tx=null;
    @Before
    public void before(){
        factory = Persistence.createEntityManagerFactory("mysql");
        manager = factory.createEntityManager();
        tx = manager.getTransaction();
        tx.begin();
    }

    @After
    public void after(){
        tx.commit();
        manager.close();
        factory.close();
    }

Then let’s take a look at the core code

new code

    @Test
    public void test01(){
        User user=new User();
        user.setUsername("zx");
        user.setAddress("Jiexi");
        user.setBirthday("2020-20-20");
        user.setSex("male");
        manager.persist(user);
    }

Code to query all data

 @Test
    public void test1() throws Exception{
        String jpql="from User";
        Query query = manager.createQuery(jpql);
        List<User> userList = query.getResultList();
        for (User user : userList) {
            System.out.println(user);
        }
    }

Note that this “from User”, User is an entity class, do not write it as the table name user

There are no examples with many names here. Of course, sql statements can also be used. This is a special case. All are still uppercase User.

//Statistical query
    @Test
    public void test4() throws Exception{
        String jpql="select count(*) from User";
        Query query = manager.createQuery(jpql);
        Object count = query.getSingleResult();
        System.out.println(count);
    }

5.SpringDataJPA

Spring Data JPA is a set of JPA application frameworks encapsulated by Spring based on the ORM framework and JPA specifications. To put it simply, the previous JPA has already stood at the number one position, but SPringDataJPA is still above it and can go directly to Life is at its peak.

The entity class is the same as JPA. Here we talk about the dao interface;

/**
 * JpaRepository<entity class, id type>: ordinary addition, deletion, modification and query
 * JpaSpecificationExecutor<entity class>: used for complex multi-condition queries
 */
@Repository
public interface UserDao extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User> {
    
}

But CRUD is different from JPA.

There are many ways to do it

@Repository
public interface UserDao extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User> {
    //User here is the entity class in the entity, not the table name of the database
    @Query("from User")
    List<User> findAll();

    @Query("from User where id=?1")
    Optional<User> findById(Integer id);

    @Query("update User set username=?1 where id=?2")
    @Modifying
    //Prevent rollback
    void update(String username, Integer id);

    //Original sql data, the label here is the database table user
    @Query(value = "select * from user where id= ?1", nativeQuery = true)
    User findById_SQL(Integer id);

    @Query(value = "delete from user where id=?1", nativeQuery = true)
    @Modifying
    void deleteById_SQL(int id);

    //Naming rule query
    User findByUsername(String username);

    List<User> findByUsernameLike(String username);
    List<User> findByUsernameLikeOrderByIdDesc(String username);
}

1. Like JPA, you can query all directly “from User”

2. Write the sql statement. Please note that when deleting or modifying these operations, we must prevent them from being rolled back.

3.SpringDataJPA provides some naming rules. As long as the method name is written correctly, there is no need to write any SQL. Just call this method and it will be ok.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring.xml")
public class Demo01 {
    @Autowired
    private UserDao userDao;
   //Naming rule query
    @Test
    public void test001() throws Exception{
        User user = userDao.findByUsername("李思");
        System.out.println(user);
    }

}

This article is not very detailed, just have a general understanding of these two.

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeJava OverviewMaven Basics 138746 people are learning the system