最近刚开始接触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-8spring: 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接口
@Repositorypublic interface SysOrderRepository extends JpaRepository{ List findByOrderID(String orderID);}
最后创建控制器
@SpringBootApplication@RestControllerpublic class Application { @Autowired SysOrderRepository orderRepository; @RequestMapping("/order/{orderId}") public String getOrderInfo(@PathVariable String orderId){ Listorder = orderRepository.findByOrderID(orderId); return order.get(0).getPayerName(); } public static void main(String[] args) throws Exception{ SpringApplication.run(Application.class,args); }}
启动项目,测试代码,完成!