当前位置 > it书童 > java > 正文

SpringBoot 整合 Spring Data JPA

java it书童 2020-11-21 18:24:11 0赞 0踩 28阅读 0评论

添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<!-- 还需要添加 mysql 依赖 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

配置数据库和 jpa 的相关属性

application.properties 配置数据

# 数据库连接
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3307/test?useSSL=false&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root

# 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.ImprovedNamingStrateg

创建实体配置实体

@Entity
@Data
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String password;
    private String name;
}

编写 UserRepository

public interface UserRepository extends JpaRepository<User, Long> {
    public List<User> findAll();
}

编写测试类

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MySpringBootApplication.class)
public class JpaTest {
    
    @Autowired
    private UserRepository userRepository;
    
    @Test
    public void test() {
        List<User> users = userRepository.findAll();
        System.out.println(users);
    }
    
}

源码 javaDemo e8153f2

关于我
一个文科出身的程序员,追求做个有趣的人,传播有价值的知识,微信公众号主要分享读书思考心得,不会有代码类文章,非程序员的同学请放心订阅
转载须注明出处:https://www.itshutong.com/articles/845