JPA连接数据库
1.pom.xml 配置maven依赖
<!-- MYSQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 2.Spring Boot JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
2.属性配置文件(application.properties)
spring.datasource.url=jdbc:mysql://localhost:3306/springboot
spring.datasource.username=root
spring.datasource.password=bwyp
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#JPA
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
3.Jpa.java
package cn.wuyang.springboot.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="jpa")
public class Jpa {
@Id //主键
@GeneratedValue //自增
private int jpa_id;
@Column(name="jpa_name")
private String jpa_name;
public int getJpa_id() {
return jpa_id;
}
public void setJpa_id(int jpa_id) {
this.jpa_id = jpa_id;
}
public String getJpa_name() {
return jpa_name;
}
public void setJpa_name(String jpa_name) {
this.jpa_name = jpa_name;
}
}
运行会自动生成对应表
4.JpaController.java
package cn.wuyang.springboot.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import cn.wuyang.springboot.dao.JpaDao;
import cn.wuyang.springboot.entity.Jpa;
@RestController
@RequestMapping("/jpa")
public class JpaController {
@Autowired
private JpaDao jpaDao;
/**
* 获取列表
* @return
*/
@RequestMapping("/list")
public List<Jpa> jpaList(){
return jpaDao.findAll();
}
/**
* 保存
* @param jpa_name
* @return
*/
@RequestMapping("/add")
public Jpa add(@RequestParam("jpa_name") String jpa_name) {
Jpa jpa = new Jpa();
jpa.setJpa_name(jpa_name);
return jpaDao.save(jpa);
}
/**
* 根据id查询
* @param id
* @return
*/
@RequestMapping("/findbyid/{id}")
public Jpa findbyid(@PathVariable("id") Integer id) {
return jpaDao.findOne(id);
}
}
5.JpaDao.java
package cn.wuyang.springboot.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import cn.wuyang.springboot.entity.Jpa;
/**
* 继承JpaRepository
* @author wuyang
*
*/
public interface JpaDao extends JpaRepository<Jpa, Integer> {
}
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/11257.html