JPA入门
2019-03-13 14:51 雄风狂飙 阅读(177) 评论(0) 收藏 举报1. JPA
1.1. JPA with H2
参考spring官网新建项目
entity:
src\main\java\hello\Customer.java
package hello;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
protected Customer(){}
public Customer(String firstName,String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
public String toString(){
return String.format(
"customer[id=%d,firstName='%s',lastName='%s']",
id,firstName,lastName);
}
}
src\main\java\hello\CustomerRepository.java
package hello;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface CustomerRepository extends CrudRepository<Customer,Long> {
List<Customer> findByLastName(String lastName);
}
src\main\java\hello\Application.java
package hello;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String []args){
SpringApplication.run(Application.class);
}
@Bean
public CommandLineRunner demo(CustomerRepository repository){
return(args) -> {
repository.save(new Customer("Jack","Bauer"));
repository.save(new Customer("Chloe","O'brian"));
repository.save(new Customer("Kim","Bauer"));
repository.save(new Customer("David","Palmer"));
repository.save(new Customer("Michelle","Dessler"));
log.info("Customers found with finaAll():");
log.info("------------------------------");
for( Customer customer:repository.findAll()){
log.info(customer.toString());
}
log.info("");
repository.findById(1L)
.ifPresent(customer->{
log.info("Customer found with findById(1L):");
log.info("---------------------------------");
log.info(customer.toString());
log.info("");
});
log.info("customer found with findBylastName('Bauer')");
repository.findByLastName("Bauer").forEach(bauer->{
log.info(bauer.toString());
});
log.info("");
};
}
}
1.2. JPA with mysql
在1.3.1的基础上进行如下修改:
1. 新增文件src\main\resources\application.properties
spring.jpa.hibername.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/mysql
spring.datasource.username=root
spring.datasource.password=123456
2. 修改pom.xml,作如下修改:
<!--<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
3. 数据库新增表:
CREATE TABLE `NewTable` (
`ID` int(10) NOT NULL AUTO_INCREMENT ,
`first_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL ,
`last_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL ,
PRIMARY KEY (`ID`)
)
ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
ROW_FORMAT=DYNAMIC
;
4. 构建
手工执行:mvnw spring-boot:run
5. 执行后效果:

问题:
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:2.0.5.RELEASE:run (default-cli) on project gs-accessing-data-jpa: An exception occurred while running. null: InvocationTar
getException: Failed to execute CommandLineRunner: error performing isolated work; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: error performing isolated work: Table 'mysql
.hibernate_sequence' doesn't exist -> [Help 1]
解决:
对实体进行修改,GenerationType.AUTO -> GenerationType.IDENTITY
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
问题:
The database returned no natively generated identity value
解决:
将对应字段,勾选自动递增,并设为主键
1.3. jpa with mysql for Web
来源:https://spring.io/guides/gs/accessing-data-mysql/
1. pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>gs-mysql-data</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Use MySQL Connector-J -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2. 目录结构

3. 相关文件
Users.java
package hello;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Users {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String email;
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
}
UserRepository.java
package hello;
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository<Users,Integer> {
}
MainController.java
package hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(path="/demo")
public class MainController {
@Autowired
private UserRepository userRepository;
@GetMapping(path="/add")
public @ResponseBody String addNewUser(
@RequestParam String name, @RequestParam String email){
Users u = new Users();
u.setName(name);
u.setEmail(email);
userRepository.save(u);
return "saved";
}
@GetMapping(path="/all")
public @ResponseBody Iterable<Users> getAllUsers(){
return userRepository.findAll();
}
}
Application.java
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String []args){
SpringApplication.run(Application.class,args);
}
}
数据库中表:
CREATE TABLE `NewTable` (
`id` int(10) NOT NULL AUTO_INCREMENT ,
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL ,
`email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL ,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
ROW_FORMAT=DYNAMIC
;
4. 测试
http://127.0.0.1:8080/demo/add?name=yangpb&email=123@123.com
返回:saved
http://127.0.0.1:8080/demo/all
返回:
[{"id":1,"name":"yangpb","email":"123@123.com"}]
浙公网安备 33010602011771号