SpringBoot学习笔记之操作mysql数据库
2017-07-24 本文已影响0人
jerrybw
spring-data-jpa
Spring-data-jpa依赖于Hibernate
在pom.xml中引入spring-data-jpa与mysql的依赖
<!-- SpringData-Jpa依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- mysql驱动:com.mysql.jdbc.Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
在主配置文件中添加配置
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url : jdbc:mysql://127.0.0.1:3306/testdb
username: root
password: root
jpa:
hibernate:
ddl-auto: create
show-sql: true
spring.jpa.properties.hibernate.ddl.auto是hibernate的配置属性,主要作用是:自动创建、更新、验证数据库表结构
创建实体类
补充说明
@id的导入要使用
import javax.persistence.Id;
否则启动会报错
@Entity//实体类
public class User{
@Id//主键
@GeneratedValue//自增
private Integer id;
private String name;
private Integer age;
//必须要有一个空参构造器
public User() {
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name= name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
dao层
public interface UserRepostory extends JpaRepository<User,Long> {
UserfindByName(String name);
@Query("from User u where u.id=:id")
User (@Param("id") Integer id);
}
接口JpaRepository的源代码
JpaRepository