一、服务启动类、pom.xml文件
@EnableEurekaClient //这里用到用到注册功能、表示该应用作为客户端注册到Eureka @SpringBootApplication public class OrderServer { public static void main(String[] args) { new SpringApplicationBuilder(OrderServer.class).web(true).run(args); } }
<!-- SpringData-Jpa依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- mysql驱动:com.mysql.jdbc.Driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.29</version> </dependency>
二、配置服务注册地址boostrap.yml、数据库配置application.yml--这里配置文件分开,方便维护
bootstrap.yml
spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/order_test?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&userSSL=false username: root password: root jpa: database: MYSQL hibernate: ddl-auto: update dialect: org.hibernate.dialect.MySQL5InnoDBDialect show-sql: true
application.yml
server: port: 9014 spring: application: name: springCloud-order eureka: instance: hostname: localhost client: register-with-eureka: true #作为服务注册 fetch-registry: false #不需要同步数据 service-url: defaultZone: http://localhost:9001/eureka/
三、编写接口--这里是新增操作,继承JpaRepository时已经具备基本的增删该查,原生sql要自己定义@query注解
@Entity @Table(name = "t_order") public class Order { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) //这里的ID选择自增 private Long id; @Column(name = "num",nullable = false) private Long num; public Product(){ } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getNum() { return num; } public void setNum(Long num) { this.num = num; } }
@Repository public interface OrderRepository extends JpaRepository<Order,Long> { }
四、编写接口和实现类
public interface OrderService { void save(Order order); }
@Service public class OrderServiceImpl implements OrderService { @Autowired private OrderRepository orderRepository; @Override public void save(Order order) { orderRepository.save(order); } }
五、controller层调用
@RestController @RequestMapping("/order") public class OrderContorller { @Autowired private OrderService orderService; @RequestMapping("/save") public void save(@RequestBody Order order){ orderService.save(order); } }