官方教程和 Demo:https://spring.io/guides/gs/accessing-data-mysql/
pom.xml 增加依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency>
初始化数据库:
create database db_example;create user 'springuser'@'%' identified by 'ThePassword';grant all on db_example.* to 'springuser'@'%';
application.properties:
# 自动建表spring.jpa.hibernate.ddl-auto=updatespring.datasource.url=jdbc:mysql://192.168.198.155:30306/db_examplespring.datasource.username=springuserspring.datasource.password=ThePasswordspring.datasource.driver-class-name =com.mysql.jdbc.Driver#spring.jpa.show-sql: true
直接使用 connection:
@Controllerpublic class HelloControl {@Autowired private DataSource dataSource;@RequestMapping("/")@ResponseBodypublic String hello() throws Exception {Connection connection = dataSource.getConnection();ResultSet rs = connection.getMetaData().getTables(null, null, null, new String[] {"TABLE"});List<String> tables = new LinkedList<>();while (rs.next()) {tables.add(rs.getString("TABLE_NAME"));}return tables.toString();}}
使用 jpa 做对象映射:
UserRepository.java
package com.example.accessingdatamysql;import org.springframework.data.repository.CrudRepository;import com.example.accessingdatamysql.User;public interface UserRepository extends CrudRepository<User, Integer> {}
User.java
package com.example.accessingdatamysql;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;@Entity // This tells Hibernate to make a table out of this classpublic class User {@Id@GeneratedValue(strategy=GenerationType.AUTO)private Integer id;private String name;private String email;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}}
MainController.java:
@Controller@RequestMapping(path = "/demo")public class MainController {@Autowiredprivate UserRepository userRepository;@PostMapping(path = "/add")public @ResponseBodyString addNewUser(@RequestParam String name, @RequestParam String email) {User n = new User();n.setName(name);n.setEmail(email);userRepository.save(n);return "Saved";}@GetMapping(path = "/all")public @ResponseBodyIterable<User> getAllUsers() {return userRepository.findAll();}}
访问:
curl -XPOST "http://localhost:8080/demo/add?name=zlj&email=zlj@qq.com"
curl http://localhost:8080/demo/all
