spring-boot
Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”. We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.
集成spring boot 和spring data jpa
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
spring boot 配置文件 application.yml
server:
port: 8081
spring:
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/demo
username: xxx
password: xxx
jpa:
hibernate:
ddl-auto: update
show-sql: true
新建spring boot类
@SpringBootApplication
public class Example {
public static void main(String[] args) {
SpringApplication.run(Example.class, args);
}
}
新建Controller
@RestController
public class HelloController {
@Autowired
private UserRepository userRepository;
@RequestMapping("/")
public String home() {
return "Hello World!";
}
@GetMapping("/getUsers")
public List<User> getAllUsers() {
return userRepository.findAll();
}
@PostMapping("/addUser")
public void getUserById(@RequestParam(value = "name") String name,@RequestParam(value = "age") Integer age) {
User user = new User();
user.setName(name);
user.setAge(age);
userRepository.save(user);
}
}
新建实体类
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private Integer age;
private Integer phone;
private String email;
get...
set...
}
新建Repository
public interface UserRepository extends JpaRepository<User,Integer> {
}