1、在pom.xml文件中,添加对JPA、JDBC、mysql等依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2、编写application.yml (application.xml)配置文件
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.1.155/jpa
driver-class-name: com.mysql.jdbc.Driver
jpa:
hibernate:
ddl-auto: update #更新或者创建数据表结构
show-sql: true #显示SQL语句
3、创建实体类
@Entity
@Table(name = "table_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "user_name" ,length = 30)
private String name;
private Integer age;
//...get/set方法省略
}
注解说明:
使用@Entity注解,标注这个类是一个实体类,对应数据库中的一张表
使用@Table注解,给表命名,可以省略,默认为类名小写
使用@Id注解,表明该属性为主键,配合@GeneratedValue注解,可以配置主键生成策略
使用@Column注解,可以配置列相关属性(列名,长度等),可以省略,默认为属性名小写
4、创建接口,继承JpaRepository接口,只需要声明即可
public interface UserRepository extends JpaRepository<User,Integer> {
}
在泛型参数中,第一个泛型参数为对应的实体类,第二个参数为主键属性的类型
5、编写controller测试
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("/user/get/{id}")
public User getUserById(@PathVariable("id") Integer id){
User user = null;
user = userRepository.findById(id).get();
//user = userRepository.getOne(id);
return user;
}
@GetMapping("/user/all")
public List<User> getUserAll(){
return userRepository.findAll();
}
@GetMapping("/user")
public List<User> insertUser(User user){
userRepository.save(user);
return userRepository.findAll();
}
}
6、遇到的问题(尚未解决)
测试代码:
@GetMapping("/user/get/{id}")
public User getUserById(@PathVariable("id") Integer id){
User user = null;
//user = userRepository.findById(id).get();
user = userRepository.getOne(id);
return user;
}
控制台信息:
Hibernate: select user0_.id as id1_0_0_, user0_.age as age2_0_0_, user0_.user_name as user_nam3_0_0_ from table_user user0_ where user0_.id=?
2018-11-06 16:01:53.560 ERROR 11692 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: me.xf.dataJPA.entity.User$HibernateProxy$Q0VHZtxA["hibernateLazyInitializer"])] with root cause
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: me.xf.dataJPA.entity.User$HibernateProxy$Q0VHZtxA["hibernateLazyInitializer"])
at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:77) ~[jackson-databind-2.9.7.jar:2.9.7]
at com.fasterxml.jackson.databind.SerializerProvider.reportBadDefinition(SerializerProvider.java:1191) ~[jackson-databind-2.9.7.jar:2.9.7]
at com.fasterxml.jackson.databind.DatabindContext.reportBadDefinition(DatabindContext.java:313) ~[jackson-databind-2.9.7.jar:2.9.7]
at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:71) ~[jackson-databind-2.9.7.jar:2.9.7]
SQL语句已经正常打印输出,控制台后续报错:类型定义错误,没有为类找到序列化程序。
使用findById(id).get()方法可以得到期望的User对象,findById()方法,其返回值是一个Optional<T>,Optional类是一个可以为null的容器对象,Optional 类的引入很好的解决空指针异常问题,然后调用它的get方法,可以获取到存入容器中的对象。