简单查询
spring data jpa是spring全家桶成员之一,用于操作各种数据库,下面写一个查询订单的简单示例
- 引入sqlserver驱动包及jpa所需包
- implementation('org.springframework.boot:spring-boot-starter-data-jpa')
- runtimeOnly('com.microsoft.sqlserver:mssql-jdbc')
2.配置连接字符串
- spring.datasource.url=jdbc:sqlserver://machinename or ip:1433;database=dbname
- spring.datasource.username=username
- spring.datasource.password=password
- spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
- spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
- #关闭初始化数据库
- spring.jpa.generate-ddl=false
- #显示生成的sql
- spring.jpa.show-sql=true
3.创建entity,可用idea生成
- @Entity
- @Table(name = "Order", schema = "dbo")
- class OrderEntity {
- @get:Id
- @get:Column(name = "OrderID")
- var orderId: String? = null
- @get:Basic
- @get:Column(name = "OrderStatus")
- var orderStatus: Byte = 0
- @get:Basic
- @get:Column(name = "OrderDate")
- var orderDate: LocalDateTime? = null
- @get:Basic
- @get:Column(name = "CurrencyCode")
- var currencyCode: String? = null
- @get:Basic
- @get:Column(name = "OrderAmount")
- var orderAmount: BigDecimal? = null
- }
4.创建repository
- @Repository
- interface OrderRepository:JpaRepository<OrderEntity,String>
可以简单调用一下了
- @Autowired
- private lateinit var orderRepository: OrderRepository
-
- orderRepository.findAll()