1. 程式人生 > >springboot jpa 連線資料庫

springboot jpa 連線資料庫

1:在pom.xml 中新增依賴

<!-- MYSQL -->
 <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
 </dependency>
 <!-- Spring Boot JPA -->
 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
 </dependency>
2:資料庫連線的配置和其它配置
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/spring-boot-security?useUnicode=true&characterEncoding=UTF-8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.show-sql=true

spring.jpa.hibernate.ddl-auto=update

3:建立一個實體類

@Entity
@Table(name = "score")
public class Score implements Serializable {

    private static final long serialVersionUID = 8127035730921338189L;

    @Id
    @GeneratedValue
    private int id;

    @Column(nullable = false, name="STUDENTID") // 這裡說一下,我使用指定資料庫列的時候,使用小寫會不起作用,修改為大寫便正常了。不知道為何,如果遇到一樣問題的可以嘗試下。
    private int stuId;

    @Column(nullable = false, name="SUBJECTNAME")
    private String subjectName;

    @Column(nullable = false)
    private float score;

    @Column(nullable = false, name="EXAMTIME")
    private Date examTime; 

    // 省去get、set 方法(佔用文章空間)

}
4:建立一個介面然後我們繼承框架為我們提供好的介面 Repository 或 CrudRepository (CrudRepository 繼承自 Repository),其中為我們提供了對資料庫的基本操作方法。如果你其中使用了修改、新增、刪除操作,則必須要在介面上面或者對應的方法上面新增 @Transactional 註解,否則會丟擲異常。
public interface IScoreDao extends CrudRepository<Score, Integer> {

    @Transactional
    @Modifying  //修改和刪除需要這個配置
    @Query("update Score t set t.score = :score where t.id = :id")
    int updateScoreById(@Param("score") float score, @Param("id") int id);

    @Query("select t from Score t ")
    List<Score> getList();

}
5:controller層
@RestController
@RequestMapping("/score")
public class ScoreController {

    private static final Logger logger = LoggerFactory.getLogger(ScoreController.class);

    @Autowired
    private IScoreDao scoreService;

    @RequestMapping("/scoreList")
    public List<Score> getScoreList(){
        logger.info("從資料庫讀取Score集合");
        // 測試更新資料庫
        logger.info("更新的行數:" + scoreService.updateScoreById(88.8f, 2));
        scoreService.delete(23);

        return scoreService.getList();
    }
}