spring-data-jpa

1:依赖

 <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-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </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>

2:配置参数

spring:
  datasource:
    username: root
    password: qwe123456
    url: jdbc:mysql://47.115.52.176:3305/jpa
    driver-class-name: com.mysql.cj.jdbc.Driver

3:写代码

Repository

自定义方法

public interface UserRepository extends JpaRepository<User,Integer> {
}

实体类

User


//使用JPA注解配置映射关系
@Entity //告诉JPA这是一个实体类(和数据表映射的类)
@Table(name = "tbl_user") //@Table来指定和哪个数据表对应;如果省略默认表名就是user;如果数据库中没有这个表,就自动创建表
//在此标记不生成json对象的属性
@JsonIgnoreProperties(value = {"hibernateLazyInitializer"})
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    @Id //这是一个主键
    @GeneratedValue(strategy = GenerationType.IDENTITY)//自增主键
    private Integer id;

    @Column(name = "last_name", length = 50) //这是和数据表对应的一个列
    private String lastName;
    @Column //省略默认列名就是属性名
    private String email;
}

controller

jap对应单表来说比较方便,不用写sql语句

@RestController
public class UserController {

    @Autowired
    UserRepository userRepository;
	//查询
    @GetMapping("/query/{id}")
    public User getUser(@PathVariable("id") int id){
        User user = userRepository.getOne(id);
        return user;
    }
	//插入
    @GetMapping("/insert")
    public User insert(User user){
        User save = userRepository.save(user);
        return save;
    }

}

4:测试

这里要在application.yml设置属性,这样如果数据中没有表,就会根据实体类设计的属性来建表

jpa:
    hibernate:
      #     更新或者创建数据表结构
      ddl-auto: update

    #    控制台显示SQL
    show-sql: true

spring-data-jpa

上一篇:Spring Data开发手册|Java持久化API(JPA)需要了解到什么程度呢?


下一篇:jpa使用jpql 原生sql 方法命名规则 实现多表联查和分页