spring boot 中使用JPA

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方法,可以获取到存入容器中的对象。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
Spring Boot 使用 JPA需要以下步骤: 1. 添加 JPA 依赖 在 pom.xml 文件添加如下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> ``` 2. 配置数据源 在 application.properties 文件添加数据源配置,例如: ``` spring.datasource.url=jdbc:mysql://localhost:3306/demo spring.datasource.username=root spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 3. 创建实体类 创建与数据库表对应的实体类,例如: ``` @Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") private String name; @Column(name = "age") private int age; } ``` 4. 创建 Repository 接口 创建一个继承 JpaRepository 的 Repository 接口,例如: ``` public interface UserRepository extends JpaRepository<User, Long> { } ``` 5. 使用 Repository 在需要使用数据库操作的地方注入 UserRepository,并使用其提供的方法进行数据库操作,例如: ``` @Service public class UserService { @Autowired private UserRepository userRepository; public List<User> getAllUsers() { return userRepository.findAll(); } public User getUserById(Long id) { return userRepository.findById(id).orElse(null); } public User saveUser(User user) { return userRepository.save(user); } public void deleteUserById(Long id) { userRepository.deleteById(id); } } ``` 以上就是在 Spring Boot 使用 JPA 的基本步骤,当然在实际应用还需要更多的配置和处理,例如事务管理等。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值