Springboot jpa 的用法

2020-01-27  本文已影响0人  楚长铭

依赖

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    runtimeOnly 'mysql:mysql-connector-java'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}

启动注解

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

//使用@createBy需要的注解
@EnableJpaAuditing 

//table实体类所在包
@EntityScan("com.ladyishenlong.jpaproject.model")

//jpa接口所在包
@EnableJpaRepositories("jpa")

@SpringBootApplication
public class JpaProjectApplication {

    public static void main(String[] args) {
        SpringApplication.run(JpaProjectApplication.class, args);
    }

}

建表

import lombok.Data;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import java.util.Date;

@Data
@MappedSuperclass
public class BaseTable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @CreatedDate
    private Date createTime;

    @CreatedBy
    private String createBy;

    @LastModifiedDate
    private Date lastModifyTime;

    @LastModifiedBy
    private String lastModifyBy;

}
@Configuration
public class UserAuditorAware implements AuditorAware<String> {
    @Override
    public Optional<String> getCurrentAuditor() {
        //常用security框架来传入用户名
        //SecurityContext ctx = SecurityContextHolder.getContext();
        return Optional.of("我是用户名");
    }
}
@Data
@Entity
@Table(name = "profession")
@EqualsAndHashCode(callSuper = true)
@EntityListeners(AuditingEntityListener.class)
public class ProfessionTable extends BaseTable {

    private String proName;
}

@Data
@Entity
@Table(name = "student")
@EqualsAndHashCode(callSuper = true)
@EntityListeners(AuditingEntityListener.class)
public class StudentTable extends BaseTable {

    private String name;

    @Column(name = "pro_id")
    private int proId;


    @OneToOne
    @JoinColumn(name = "pro_id", referencedColumnName = "id",
            insertable = false, updatable = false)
    private ProfessionTable profession;

}

JPA

public interface StudentJpa extends JpaRepository<StudentTable, Integer> {


    List<StudentTable> findAllById(int id);

    @Query("select i from StudentTable i where i.id=:id")
    List<StudentTable> getById(@Param("id") int id);
    

    @Query(nativeQuery = true,
            value = "select * from student where id = :id ")
    List<Map<String, Object>> getNamesById(@Param("id") int id);


}
[
    {
        "id": 1,
        "createTime": null,
        "createBy": null,
        "lastModifyTime": null,
        "lastModifyBy": null,
        "name": "藤丸立香",
        "proId": 1,
        "profession": {
            "id": 1,
            "createTime": null,
            "createBy": null,
            "lastModifyTime": null,
            "lastModifyBy": null,
            "proName": "人理修复"
        }
    }
]

dto

public interface StudentDto {
    String getName();
}
   @Query("select i.name as name from StudentTable  i")
    List<StudentDto> getNames();

-查询结果示例

[
    {
        "name": "藤丸立香"
    },
    {
        "name": "阿提拉"
    }
]
@Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;

    
    @Transactional
    public Object hello() {

        List<Integer> pa = new ArrayList<Integer>() {{
            this.add(1);
        }};
        SqlParameterSource[] batchArgs = new SqlParameterSource[pa.size()];

        for (int i = 0; i < pa.size(); i++) {
            HashMap<String, Object> param = new HashMap<>();
            param.put("name", "名字");
            param.put("id", pa.get(i));
            batchArgs[i] = new MapSqlParameterSource(param);
        }
        String sql = "update student set name=:name where id=:id";
        jdbcTemplate.batchUpdate(sql, batchArgs);

        return null;
    }
上一篇 下一篇

猜你喜欢

热点阅读