Spring Boot之使用JPA操作mysql

2018-03-01 11:04:18来源:oschina作者:webxiaohua人点击

分享

最近刚开始接触spring boot,写了一个操作db的demo,在此记录一下


项目采用maven构建,首先在pom文件中引入spring boot



org.springframework.boot
spring-boot-starter-parent
1.4.2.RELEASE

添加依赖(包括spring boot启动依赖、jpa、mysql、lombok)




org.springframework.boot
spring-boot-starter-web


org.springframework.boot
spring-boot-starter-data-jpa


mysql
mysql-connector-java


org.projectlombok
lombok
compile


然后在src/main/ersources目录下新建application.yml文件(application.properties也可以,只是yml文件更方便写配置),配置服务端口、编码、db连接串、jpa策略等等,配置文件内容如下:


server:
port: 8080
tomcat:
uri-encoding: UTF-8
spring:
datasource:
url: jdbc:mysql://localhost:3306/monitor?useSSL=false
username: root
password: root
tomcat:
max-active: 100
max-idle: 200
initial-size: 20
jpa:
database-platform: org.hibernate.dialect.MySQL5Dialect
hibernate:
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

下面开始进入编码,首先创建entity类


@Data
@Entity
@Table(name="sys_order")
public class SysOrder {
@Id
private String id;
@Column(name="PayerName")
private String payerName;
@Column(name="OrderID")
private String orderID;
@Column(name="PayResult")
private String payResult;
@Column(name="Remark")
private String remark;
@Column(name="CreatedTime")
private String createdTime;
}

然后创建一个repository接口


@Repository
public interface SysOrderRepository extends JpaRepository{
List findByOrderID(String orderID);
}

最后创建控制器


@SpringBootApplication
@RestController
public class Application {
@Autowired
SysOrderRepository orderRepository;
@RequestMapping("/order/{orderId}")
public String getOrderInfo(@PathVariable String orderId){
List order = orderRepository.findByOrderID(orderId);
return order.get(0).getPayerName();
}
public static void main(String[] args) throws Exception{
SpringApplication.run(Application.class,args);
}
}

启动项目,测试代码,完成!

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台