Home  >  Article  >  Java  >  Detailed explanation of examples of java database operations through JPA

Detailed explanation of examples of java database operations through JPA

Y2J
Y2JOriginal
2017-05-06 13:19:152995browse

Today I will introduce to you how to connect to the Mysql database in SpringBoot and use JPA to perform database-related operations.

Today I will introduce to you how to connect to the Mysql database in SpringBoot and use JPA to perform database-related operations.

Step 1: Add the related Jar package dependencies of MYSQl and JPA in the pom.xml file. The specific addition location is in dependencies. The specific added content is as follows.

<!--数据库相关配置--> 
    <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-web</artifactId> 
    </dependency> 
    <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-data-jpa</artifactId> 
    </dependency> 
    <dependency> 
      <groupId>mysql</groupId> 
      <artifactId>mysql-connector-java</artifactId> 
    </dependency> 
    <dependency> 
      <groupId>org.apache.poi</groupId> 
      <artifactId>poi</artifactId> 
      <version>3.11</version> 
    </dependency>

Step 2: Add the relevant configuration of the database to the application.properties configuration file. The configuration information is as follows.

spring.datasource.url = jdbc:mysql://localhost:3306/webtest 
spring.datasource.username = root 
spring.datasource.password = 220316 
spring.datasource.driverClassName = com.mysql.jdbc.Driver 
# Specify the DBMS 
spring.jpa.database = MYSQL 
# Show or not log for each sql query 
spring.jpa.show-sql = true 
# Hibernate ddl auto (create, create-drop, update) 
spring.jpa.hibernate.ddl-auto = update 
# Naming strategy 
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy 
# stripped before adding them to the entity manager) 
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

Here is an explanation: webtest represents the database name, root is the user name, and 220316 is the password

Step 3: Write database operation entity class, the specific information of the entity class is as follows:

package example.entity; 
import javax.persistence.*; 
import javax.validation.constraints.NotNull; 
import java.math.BigDecimal; 
import java.util.Date; 
@Entity 
@Table(name = "user") 
public class User { 
  @Id 
  @GeneratedValue(strategy = GenerationType.AUTO) 
  private int id; 
 
  @Column(name = "name", nullable = true, length = 30) 
  private String name; 
 
  @Column(name = "height", nullable = true, length = 10) 
  private int height; 
 
  @Column(name = "sex", nullable = true, length = 2) 
  private char sex; 
 
  @Temporal(TemporalType.DATE) 
  private Date birthday; 
 
  @Temporal(TemporalType.TIMESTAMP) 
  private Date sendtime; // 日期类型,格式:yyyy-MM-dd HH:mm:ss 
 
  @Column(name = "price", nullable = true, length = 10) 
  private BigDecimal price; 
 
  @Column(name = "floatprice", nullable = true, length = 10) 
  private float floatprice; 
 
 
  @Column(name = "doubleprice", nullable = true, length = 10) 
  private double doubleprice; 
 
  public Date getSendtime() { 
    return sendtime; 
  } 
 
  public void setSendtime(Date sendtime) { 
    this.sendtime = sendtime; 
  } 
 
  public BigDecimal getPrice() { 
    return price; 
  } 
 
  public void setPrice(BigDecimal price) { 
    this.price = price; 
  } 
 
  public float getFloatprice() { 
    return floatprice; 
  } 
 
  public void setFloatprice(float floatprice) { 
    this.floatprice = floatprice; 
  } 
 
  public double getDoubleprice() { 
    return doubleprice; 
  } 
 
  public void setDoubleprice(double doubleprice) { 
    this.doubleprice = doubleprice; 
  } 
 
  public User() { } 
 
  public char getSex() { 
    return sex; 
  } 
 
  public void setSex(char sex) { 
    this.sex = sex; 
  } 
 
  public Date getBirthday() { 
    return birthday; 
  } 
 
  public void setBirthday(Date birthday) { 
    this.birthday = birthday; 
  } 
 
  public User(int id) { 
    this.id = id; 
  } 
 
  public int getId() { 
    return id; 
  } 
 
  public void setId(int id) { 
    this.id = id; 
  } 
 
  public String getName() { 
    return name; 
  } 
 
  public void setName(String name) { 
    this.name = name; 
  } 
 
  public int getHeight() { 
    return height; 
  } 
 
  public void setHeight(int height) { 
    this.height = height; 
  } 
}

What everyone needs to pay attention to here is: the class name and field attribute in the entity class must be consistent with the table in the database and The fields correspond to each other. The following is a correspondence diagram of various attributes of MYSQL-JAVA:

Step 4: Write the data operation class of the dao layer, dao data The operation class is as follows:

package example.dao; 
import example.entity.User; 
import org.springframework.data.repository.CrudRepository; 
import javax.transaction.Transactional; 
import java.math.BigDecimal; 
import java.util.Date; 
import java.util.List; 
 
@Transactional 
public interface UserDao extends CrudRepository<User, Integer> { 
  public List<User> findByName(String name); 
  public List<User> findBySex(char sex); 
  public List<User> findByBirthday(Date birthday); 
  public List<User> findBySendtime(Date sendtime); 
  public List<User> findByPrice(BigDecimal price); 
  public List<User> findByFloatprice(float floatprice); 
  public List<User> findByDoubleprice(double doubleprice); 
}

You may have questions here, why should inherit CrudRepository0e4b54218c9a07445335f10bb61dc1ba, and what is its specific role?

I will give you a brief introduction to some common usage and usage guidelines in JPA:

1. The first thing is to inherit the CrudRepository method, which contains two The specific meaning of the two parameters is: the first parameter indicates the name of the entity class being operated, and the second parameter indicates the type of primary key in the entity class.

2. After inheriting, you can use some methods inherited from the parent class. For example, as shown above, you can use findBy+"You want to query the field name of ", through this The method can easily realize the function of SQL query.

You may still be a little confused here. Let me give you an example:

For example, the above findByName (String name) is actually equivalent to the SQL statement The select *from user where name=? . After such a comparison, you will immediately understand what this method means.

Step 5: Write the control class controller. The specific information of the control class is as follows:

package example.controller; 
import example.dao.UserDao; 
import example.entity.User; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.ResponseBody; 
import java.math.BigDecimal; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 
import java.util.List; 
@Controller 
public class UserController { 
  @Autowired 
  private UserDao userDao; 
  @RequestMapping("/getName") 
  @ResponseBody 
  public String getByName(String name) { 
    List<User> userList = userDao.findByName(name); 
    if (userList != null && userList.size()!=0) { 
      return "The user length is: " + userList.size(); 
    } 
    return "user " + name + " is not exist."; 
  } 
 
  @RequestMapping("/getSex") 
  @ResponseBody 
  public String getBySex(char sex) { 
    List<User> userList = userDao.findBySex(sex); 
    if (userList != null && userList.size()!=0) { 
      return "The user length is: " + userList.size(); 
    } 
    return "user " + sex + " is not exist."; 
  } 
 
  @RequestMapping("/getBirthday") 
  @ResponseBody 
  public String findByBirthday(String birthday) { 
    System.out.println("birthday:"+birthday); 
    SimpleDateFormat formate=new SimpleDateFormat("yyyy-MM-dd"); 
    List<User> userList = null; 
    try { 
      userList = userDao.findByBirthday(formate.parse(birthday)); 
    } catch (ParseException e) { 
      e.printStackTrace(); 
    } 
    if (userList != null && userList.size()!=0) { 
      return "The user length is: " + userList.size(); 
    } 
    return "user " + birthday + " is not exist."; 
  } 
 
  @RequestMapping("/getSendtime") 
  @ResponseBody 
  public String findBySendtime(String sendtime) { 
    System.out.println("sendtime:"+sendtime); 
    SimpleDateFormat formate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    List<User> userList = null; 
    try { 
      userList = userDao.findBySendtime(formate.parse(sendtime)); 
    } catch (ParseException e) { 
      e.printStackTrace(); 
    } 
    if (userList != null && userList.size()!=0) { 
      return "The user length is: " + userList.size(); 
    } 
    return "user " + sendtime + " is not exist."; 
  } 
 
  @RequestMapping("/getPrice") 
  @ResponseBody 
  public String findByPrice(BigDecimal price) { 
    List<User> userList = null; 
    userList = userDao.findByPrice(price); 
    if (userList != null && userList.size()!=0) { 
      return "The user length is: " + userList.size(); 
    } 
    return "user " + price + " is not exist."; 
  } 
 
  @RequestMapping("/getFloatprice") 
  @ResponseBody 
  public String findFloatprice(float floatprice) { 
    List<User> userList = null; 
    userList = userDao.findByFloatprice(floatprice); 
    if (userList != null && userList.size()!=0) { 
      return "The user length is: " + userList.size(); 
    } 
    return "user " + floatprice + " is not exist."; 
  } 
 
  @RequestMapping("/getDoubleprice") 
  @ResponseBody 
  public String findByPrice(double doubleprice) { 
    List<User> userList = null; 
    userList = userDao.findByDoubleprice(doubleprice); 
    if (userList != null && userList.size()!=0) { 
      return "The user length is: " + userList.size(); 
    } 
    return "user " + doubleprice + " is not exist."; 
  } 
}

You may have a big question here, I also ignored this problem deeply at the beginning, that is, why can userDao be used directly without instantiation?

Now I will explain to you why this is the case:

In fact, it is not that this userDao is not instantiated, but the instantiation is automatically completed by the systemof. As long as the @Autowired attribute is added above userDao, the interface can be instantiated automatically. There is no need to write any implementation classes such as userDaoImp ​​as before. This can greatly improve the simplicity of the code and the development speed.

I know that some people may still ask this question: That is automatic instantiation, but how does the instantiation know what addition, deletion, modification and check functions the dao class needs to implement? There is no such thing in the dao code. Didn't you say that? In fact, those who are interested may have discovered it. In the previous step, we explained the specific function of findBy+"field name". This is actually the answer to this question. In fact, the various methods in the dao layer are the SQl commands in the various implementation classes in daoimp. I will give you a detailed introduction to how they correspond to each other in the next section, but now I will give you a brief introduction.

Step 6: The table name and field information of the database are as follows:


[Related recommendations]

1. Java Free Video Tutorial

2. Geek Academy Java Video Tutorial

3. Ali Baba Java Development Manual

The above is the detailed content of Detailed explanation of examples of java database operations through JPA. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn