SpringBoot整合Jpa
(1)添加Spring Data JPA的起步依赖
(2)添加数据库驱动依赖
(3) 在application.properties中配置数据库和jpa的相关属性
!!!空格不能随便删除
spring:
datasource: # hikari
driver-class-name: com.mysql.cj.jdbc.Driver # mysql 8
username: root
password: 123456
url: jdbc:mysql://localhost:3306/springboot_test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
# 配置jpa PhysicalNamingStrategyStandardImpl小驼峰 xx_yy_xx
jpa:
show-sql: true
hibernate:
ddl-auto: update
naming:
physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
database: mysql
测试
@SpringBootTest
class Demo05jpa2ApplicationTests {
@Autowired
UserDao userDao;
@Test
void test01() {
User user = new User();
user.setGirlFriend("rose");
user.setUsername("jack@xx.com");
user.setName("jack");
userDao.save(user);//--->orm -- >将对象值取出-->sql-->数据库
}
}
User
@Entity //表示当前类,在数据库有表与它对应
@Table(name = "tb_user2")
public class User {
@Id //表示id
@GeneratedValue(strategy = GenerationType.IDENTITY) //主键自增长
private int id;
private String username;
private String password;
private String girlFriend;
private String name;
}
UserDao
//继承通用的接口,即可完成增删改查
public interface UserDao extends JpaRepository<User,Integer> {
}