springBoot2.x 整合 springdataJpa 测试

springBoot2.x 整合 springdataJpa 测试

pom.xml
  <properties>
        <java.version>1.8java.version>
    properties>

    <dependencies>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-jpaartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintagegroupId>
                    <artifactId>junit-vintage-engineartifactId>
                exclusion>
            exclusions>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>
yaml
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql:///jpa
    username: root
    password: 123456
  jpa:
    hibernate:
      ddl-auto: update  # 更新,没有表的时候自动建表
      show‐sql: true   # 打印sql语句
User实体类
// 使用jpa注解配置映射关系
@Entity   //声明这是一个实体类
@Table(name = "tb_user")  //与表进行对应
public class User {

    @Id  //这是一个主键
    @GeneratedValue(strategy = GenerationType.IDENTITY) //主键自增
    private Integer id;

    @Column(name = "name")  //与字段名对应
    private String name;

    @Column    //如果不声明字段名,则默认使用属性名作为字段名
    private String email;

    public User() {
    }
}
UserDao 持久层
public interface UserDao extends JpaRepository<User, Integer> {
}
Test 测试
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class SpringBoot09JpaApplicationTests {

    @Autowired
    private UserDao userDao;

    // 添加
    @Test
    public void addUser() {
        User user = new User();
        user.setName("李四");
        user.setEmail("[email protected]");

        user = userDao.save(user);  //将带有主键的对象返回

    }
    
    //查询
    @Test
    public void find_One(){

        Optional<User>  optional = userDao.findById(1);

        // 值不为空
       if(optional.isPresent()){
           User user = optional.get();
           System.out.println(user);
       }else{
           System.out.println("没有该用户");
       }

    }
}

你可能感兴趣的:(springboot)