- 导入数据库连接依赖及jpa依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
- 在application.properties文件中添加数据库连接属性及jpa配置
spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.username = root
spring.datasource.password = 123456
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
- 自定义一个javabean,并使用注解@Entity进行ORM,并在主键上添加@Id和@GeneratedValue
@Entity
public class Person {
@Id
@GeneratedValue
private long id;
private String name;
private int age;
...
其中@Id是用来标识主键的,而@GeneratedValue则是用来指定主键策略的。
- 编写持久化接口:
public interface PersonRepository extends CrudRepository<Person,Long>{
}
泛型中的第一个为要操作的对象,第二个为主键的类型,此时我们只需要对Person对象进行简单的操作,即可操作数据库的crud了。
- 调用dao接口
@Autowired
private PersonRepository personRepository;
public Person savePerson(){
Person person = new Person();
person.setName("zhangsan");
person.setAge(18);
return personRepository.save(person);
}
此时我们启动程序,启动完成后,我们发现,数据库已经自动将Person表建好,当我们调用savePerson方法后,对应的数据也已经入库了。