spring boot連線 sqlserver(1)
阿新 • • 發佈:2018-12-17
#spring boot JPA 連線SQl Server 1、首先呢載入jpa 與jdbc 相關的依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.microsoft.sqlserver</groupId> <artifactId>mssql-jdbc</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
2、在配置檔案裡配置相關的連線資料庫資訊
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.url=jdbc:sqlserver://127.0.0.1:1433; databaseName=smxTest
spring.datasource.username=sa
spring.datasource.password=zlf123456
3、編寫資料表對應的Entity檔案(若檔名不一樣,記得用@Table來指定對應的表明)用@Id指定檔案的主鍵,@GeneratedValue指定逐漸的增長方式(這裡對應的是PO層)
@Entity
@Table(name = "users")
public class usersEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
3、新建jpa檔案(interface)並整合JpaRepository<entity, 主鍵的資料型別>,下面就開始寫增刪改查了(這裡對應的應該是DAO層)
public interface UsersRespository extends JpaRepository<usersEntity, Integer> {
/**
* 獲取所有使用者資訊
* @return
*/
@Query(value = "select * from users", nativeQuery = true)
List<usersEntity> getFindAll();
}
4、下面就開始查詢用了
@RestController
public class UserController {
@Autowired
UsersRespository usersRespository;
@GetMapping("/users")
public int findAll(){
List<usersEntity> list = usersRespository.findAll();
for (usersEntity u:list) {
System.out.println(u.getName());
}
return list.size();
}
}