1.添加Spring Data JPA的起步依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
2.添加数据库驱动依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
3.在application.properties中配置数据库和jpa相关属性
#数据库连接信息
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3305/test
spring.datasource.username=root
spring.datasource.password=*****
#jpa相关属性
spring.jpa.database=mysql
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
4.创建实体配置实体
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
private String passwd;
private String name;
getter,setter方法;
toString方法;
}
5.编写UserRepository
/**接口需要集成JpaRepository
JpaRepository<Users,Long>:第一个参数代表我们的实体,第二个参数代表我们实体的ID
需要编写具体的业务方法
*/
public interface UserRepository extends JpaRepository<User,Long> {
public List<User>findAll();
}
6.编写测试类
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootJpaApplication.class)
public class JpaTest {
@Autowired
UserRepository userRepository;
@Test
public void JpaTest1(){
List<User> users = userRepository.findAll();
System.out.println(users);
}
}
7.控制台打印信息
[Users{id=1, username='郭天天', passwd='123', name='guotiantian'}, Users{id=2, username='任润斌', passwd='123', name='renrunbin'}]