赞
踩
采用idea的spring boot创建向导创建web工程demo
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--自动生成getter,setter-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
# 数据库url地址
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
dbcp2:
max-idle: 10
max-wait-millis: 10000
min-idle: 5
initial-size: 5
CREATE TABLE `employee` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
`sex` char(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
@Data
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private char sex;
}
public interface EmployeeDao extends JpaRepository<Employee, Serializable> {
}
接口
public interface EmployeeSerivce {
Employee getEmployee(Long id);
List<Employee> list();
int update(Employee employee);
int insert(Employee employee);
int delete(Long id);
}
实现类
@Service public class EmployeeServiceImpl implements EmployeeSerivce { @Autowired EmployeeDao dao; @Override public Employee getEmployee(Long id) { return dao.getOne(id); } @Override public List<Employee> list() { return dao.findAll(); } @Override public int update(Employee employee) { dao.save(employee); return 1; } @Override public int insert(Employee employee) { dao.save(employee); return 1; } @Override public int delete(Long id) { dao.deleteById(id); return 1; } }
@RestController public class EmployeeController { @Autowired private EmployeeSerivce employeeSerivce; @GetMapping(value = "/emp/{id}") public Employee getEmp(@PathVariable(value = "id") Long id){ return employeeSerivce.getEmployee(id); } @GetMapping(value = "/emp/list") public List<Employee> getEmpList(){ return employeeSerivce.list(); } @PostMapping(value = "/emp") public String insert(Employee employee){ employeeSerivce.insert(employee); return "success"; } @PutMapping(value = "/emp") public String update(Employee employee){ employeeSerivce.update(employee); return "success"; } @DeleteMapping(value = "/delete/{id}") public String delete(@PathVariable(value = "id") Long id){ employeeSerivce.delete(id); return "success"; } }
访问http://localhost:8080/emp/list
[{"id":1,"name":"admin","sex":"1"},{"id":2,"name":"guese","sex":"1"},{"id":3,"name":"whc","sex":"1"}]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。