yml配置文件:
#配置jpa jpa: database: MySQL database-platform: org.hibernate.dialect.MySQL5InnoDBDialect show-sql: true hibernate: ddl-auto: update
ddl-auto:主要存在四种属性:create,create-drop,update和validate
ddl-auto:create ----每次运行该程序,没有表格会新建表格,表内有数据会清空;
ddl-auto:create-drop ----每次程序结束的时候会清空表
ddl-auto:update ---- 每次运行程序,没有表格会新建表格,表内有数据不会清空,只会更新
ddl-auto: validate ---- 运行程序会校验数据与数据库的字段类型是否相同,不同会报错。
-------------------
1、实体类添加@Entity @Table
@Table(name="userinfo")// 这个名字会在你的数据库自动生成,所以只需要自己创建好数据库,然后jpa会自动生成。
如下:
@Id @GeneratedValue @Column(name = "Id") private int Id; @Column(name = "Name") private String Name; @Column(name = "Age") private int Age;
然后添加get ,set 方法及其构造方法
---------------------------
package com.springboot_jpa.demo.Repository;
import com.springboot_jpa.demo.entity.UserInfo;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
@Configuration
@Repository
@Transactional //事务
public interface uersRepository extends JpaRepository<UserInfo,Long> {
@Override
<S extends UserInfo> S saveAndFlush(S s);
/**
* 查询全部
* */
// @Query("from userInfo")
// public UserInfo getUerInfo(@Param("Id") Integer id,@Param("Name") String Name,@Param("Age") Integer Age);
/**
* 模糊查询
* */
/**
* 添加用户
* */
//可以自己手动写sql
// public UserInfo AddUerInfo(@Param("Id") Integer id, @Param("Name") String Name, @Param("Age") Integer Age);
//@Modifying
@Query(value = "Insert into userInfo(Name,Age) value(?,?)",nativeQuery = true)
void AddUerInfo(String name, int age);
/**
* 用户修改
* */
/**
* 删除用户
* */
@Modifying
@Query(value = "delete from userInfo where Id=? ",nativeQuery = true)
void deleteById(int Id);
}
-------------------------
service层:
//添加用户
@Override
@Transactional
public void addUserInfo(UserInfo user) {
String string=uersRepository.saveAndFlush(user).toString();
System.out.println("结果:"+string);
}
---------------------------
controller层:
@ResponseBody
@GetMapping("/save")
public JSONObject save(@RequestParam("name") String Name, @RequestParam("age") Integer Age) {
UserInfo user = new UserInfo();
user.setName(Name);
user.setAge(Age);
UserInfoServiceImpl.addUserInfo(user);
JSONObject jsonObject = UserInfoServiceImpl.getAllUserInfo();
System.out.println("查询全部:" + jsonObject.toString());
return jsonObject;
}