springboot entry - Integrated SpringDataJPA

1. Add the starting dependent Spring Data JPA

<!-- springBoot JPA的起步依赖 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

2. Add the database driver dependent

<!-- MySQL连接驱动 -->
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
</dependency>

3. jpa configuration database and associated attributes (the application.properties)

# 数据库连接信息
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://172.20.10.13:3306/test?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=11250825

# JPA Configuration:
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. Create entity (domain--User.java)

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

5. repository——UserRepository.java

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

6. write test classes

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootJpaApplication.class)
public class JpaTest {

    @Autowired
    private UserRepository userRepository;

    @Test
    public void test() {
        List<User> all = userRepository.findAll();
        System.out.println(all);
    }
}

7. Test can be.

Contrast the blog post can be found, the use of JPA, eliminating the sql statement and mapper.

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/dl674756321/article/details/91492852