ORM:springBoot使用JPA框架--入门记录

ORM:springBoot使用JPA框架–入门基础使用

新建项目
在这里插入图片描述
选择依赖
Spring Web
Spring Data JPA
Mysql Driver(根据数据库类型选择)
在这里插入图片描述
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.10</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>jpa</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mybatis</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-json</artifactId>
                </exclusion></exclusions>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-json -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-json</artifactId>
            <version>2.5.10</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>alimaven</id>
            <name>aliyun maven</name>
            <url>https://maven.aliyun.com/nexus/content/groups/public/</url>
        </repository>
    </repositories>
</project>

yml文件配置

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test
    type: com.zaxxer.hikari.HikariDataSource
    username: root
    password: ******
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

建立代码框架
entity

package com.example.jpa.entity;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "test")  //数据库表名
//@JsonIgnoreProperties(value = { "hibernateLazyInitializer"})
public class User implements Serializable {
	@Id
    @GeneratedValue
    private Long id ;
    
    @Column
    private String name;
    
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

controller

package com.example.jpa.controller;

import com.example.jpa.entity.User;
import com.example.jpa.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/testBoot")
public class UserController {
        @Autowired
        private UserService userService;

        @RequestMapping("/getUser")
        public User getUser(){
                return userService.getUser(1L);
        }

}

service & serviceImpl

package com.example.jpa.service;


import com.example.jpa.entity.User;
import org.springframework.beans.factory.annotation.Autowired;

public interface UserService {

    public User getUser(Long id);
}

package com.example.jpa.service.impl;

import com.example.jpa.dao.UserDao;
import com.example.jpa.entity.User;
import com.example.jpa.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public User getUser(Long id) {

        return userDao.getById(id);
    }
}

dao
(继承JpaRepository,可使用JpaRepository接口的方法)

package com.example.jpa.dao;

import com.example.jpa.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserDao extends JpaRepository<User,Long> {
}

如果访问接口,返回数据时报以下错:

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: com.example.jpa.entity.User$HibernateProxy$gjCWzEiZ["hibernateLazyInitializer"])

原因配置了懒加载模式,通过Spring MVC返回json序列化时报错。
通过java的反射机制将pojo转换成json的。

因为json plugin用的是java的内审机制.被管理的pojo会加入[“hibernateLazyInitializer”,“handler”,“fieldHandler”]等属性,json plugin会对这些属性拿出来操作,并读取里面一个不能被反射操作的属性就产生了异常。

解决·方法:
方法一
实体类添加注解
@JsonIgnoreProperties(value = { “hibernateLazyInitializer”})

方法二
配置文件关闭hibernateLazyInitializer
jackson:
serialization:
FAIL_ON_EMPTY_BEANS: false

//spring下面
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test
    type: com.zaxxer.hikari.HikariDataSource
    username: root
    password: ******
    driver-class-name: com.mysql.cj.jdbc.Driver
    
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    
  jackson:
    serialization:
      FAIL_ON_EMPTY_BEANS: false
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值