jpa中数据的增删改查
@Entity
@Data
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String author;
}
mapper***************
public interface BookRepository extends JpaRepository<Book,Integer> {
}
controller
@RestController
@RequestMapping("/book")
public class BookHandler {
@Autowired
private BookRepository bookRepository;
分页查询
@GetMapping("/findAll/{page}/{size}")
public Page<Book> findAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
PageRequest request = PageRequest.of(page,size);
return bookRepository.findAll(request);
}
新增
@PostMapping("/save")
public String save(@RequestBody Book book){
Book result = bookRepository.save(book);
if(result != null){
return "success";
}else{
return "error";
}
}
依据id查询
@GetMapping("/findById/{id}")
public Book findById(@PathVariable("id") Integer id){
return bookRepository.findById(id).get();
}
更新
@PutMapping("/update")
public String update(@RequestBody Book book){
Book result = bookRepository.save(book);
if(result != null){
return "success";
}else{
return "error";
}
}
删除
@DeleteMapping("/deleteById/{id}")
public void deleteById(@PathVariable("id") Integer id){
bookRepository.deleteById(id);
}
}
跨域问题解决办法
@Configuration
public class CrosConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
mybatisplus 增删改查
entity
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("m_user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@NotBlank(message = "昵称不能为空")
private String username;
private String avatar;
mapper
public interface UserMapper extends BaseMapper<User> {
}
service
public interface UserService extends IService<User> {
}
controller
@Autowired
BlogService blogService;
@GetMapping("/blogs")
public Result list(@RequestParam(defaultValue = "1") Integer currentPage) {
Page page = new Page(currentPage, 5);
IPage pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created"));
return Result.succ(pageData);
}
@GetMapping("/blog/{id}")
public Result detail(@PathVariable(name = "id") Long id) {
Blog blog = blogService.getById(id);
Assert.notNull(blog, "该博客已被删除");
return Result.succ(blog);
}
@RequiresAuthentication
@PostMapping("/blog/edit")
public Result edit(@Validated @RequestBody Blog blog) {
Blog temp = null;
if(blog.getId() != null) {
temp = blogService.getById(blog.getId());
System.out.println(ShiroUtil.getProfile().getId());
Assert.isTrue(temp.getUserId().longValue() == ShiroUtil.getProfile().getId().longValue(), "没有权限编辑");
} else {
temp = new Blog();
temp.setUserId(ShiroUtil.getProfile().getId());
temp.setCreated(LocalDateTime.now());
temp.setStatus(0);
}
BeanUtil.copyProperties(blog, temp, "id", "userId", "created", "status");
blogService.saveOrUpdate(temp);
return Result.succ(null);
}
}
mybatis 实现curd
entity
public class User {
private Integer userId;
private String userName;
private String userPwd;
mapper
public interface Usermapper {
public User selectuserbyid(Integer id);
public User selectUserByName(String userName);
public int insertUser(User user);
public int deleteUserById(int userId);
public List<User> selectUserByItem(UserQuery userQuery);
public int updateUser(User user);
}
定义映射mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.liuyang.mapper.Usermapper">
<select id="selectuserbyid" parameterType="int" resultType="com.liuyang.bean.User">
select * from t_user where user_id=#{userId}
</select>
<select id="selectUserByName" parameterType="String" resultType="com.liuyang.bean.User">
select * from t_user where user_name=#{userName}
</select>
<insert id="insertUser">
insert into t_user(user_name,user_pwd) values(#{userName},#{userPwd});
</insert>
<!--删除一条-->
<delete id="deleteUserById" parameterType="int">
delete from t_user where user_id=#{userId}
</delete>
<!--修改-->
<update id="updateUser">
update t_user set user_name=#{userName},user_pwd=#{userPwd} where user_id=#{userId}
</update>
<!--条件查询-->
<select id="selectUserByItem" resultType="com.liuyang.bean.User">
select * from t_user
<where>
<if test="userName!=null">
user_name like "%${userName}%"
</if>
</where>
</select>
</mapper>
数据元配置
## 数据源配置
spring:
## 热部署配置
devtools:
restart:
enabled: true
# 设置重启的目录,添加目录的文件需要restart
additional-paths: src/main/java
# 解决项目自动重新编译后接口报404的问题
poll-interval: 3000
quiet-period: 1000
datasource:
type: com.mchange.v2.c3p0.ComboPooledDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/springboot_mybatis?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
username: root
password: 123456
##视图的配置
freemarker:
template-loader-path: classpath*:/views/
charset: UTF-8
content-type: text/html
cache: false
suffix: .ftl
## mybatis 配置
mybatis:
#映射文件的存放路径
mapper-locations: classpath*:/mapper
@Override
public void saveUser(User user) {
AssertUtil.isTrue( StringUtils.isBlank(user.getUserName()),"用户名不能为空");
AssertUtil.isTrue(StringUtils.isBlank(user.getUserPwd()),"用户密码不能为空");
User temp = usermapper.selectUserByName(user.getUserName());
AssertUtil.isTrue(temp!=null,"用户已经存在");
AssertUtil.isTrue(usermapper.insertUser(user)<1,"添加失败了");
}
@Override
public void changeUser(User user) {
AssertUtil.isTrue( StringUtils.isBlank( user.getUserName() ),"用户名不为空" );
AssertUtil.isTrue( StringUtils.isBlank( user.getUserPwd() ),"密码不为空" );
User temp = usermapper.selectuserbyid(user.getUserId());
AssertUtil.isTrue( temp == null,"用户不存在");
AssertUtil.isTrue( usermapper.updateUser(user)<1,"修改失败了");
}
@Override
public void removeUserById(Integer userId) {
AssertUtil.isTrue( userId==null|| null==usermapper.selectuserbyid( userId ),"待删除数据不存在" );
AssertUtil.isTrue( usermapper.deleteUserById( userId )<1,"删除失败" );
}
@Override
public PageInfo<User> queryUserByPage(UserQuery userQuery) {
PageHelper.startPage( userQuery.getPageNum(),userQuery.getPageSize());
List<User> ulist = usermapper.selectUserByItem( userQuery );
PageInfo<User> plist =new PageInfo<User>(ulist);
return plist;
}
}
controller
@RestController
public class Usercontroller {
@Resource
private Usermapper usermapper;
@Resource
private Userservice userservice;
@GetMapping("one/{id}")
public User sayUser(@PathVariable Integer id) {
System.out.println( id + "<<<" );
User user = userservice.queryUserById( id );
return user;
}
@GetMapping("userOne/{name}")
public User sayUserOne(@PathVariable String name) {
System.out.println( name + "<<<" );
User user = userservice.queryUserByName( name );
return user;
}
@PutMapping("add")
public ResultInfo sayAdd(User user) {
ResultInfo result =new ResultInfo();
System.out.println(user+"<<<");
try {
userservice.saveUser( user );
} catch (ParamException ex) {
ex.printStackTrace();
result.setCode( ex.getCode() );
result.setMsg( ex.getMsg() );
}catch (Exception ex){
ex.printStackTrace();
result.setCode( 300 );
result.setMsg( "添加异常" );
}
return result;
}
@PostMapping("update")
public ResultInfo sayUpdate(@RequestBody User user){
ResultInfo result=new ResultInfo();
System.out.println(user + "<<<");
try {
userservice.changeUser( user );
} catch (ParamException ex) {
ex.printStackTrace();
result.setCode( ex.getCode() );
result.setMsg( ex.getMsg() );
}catch(Exception ex){
ex.printStackTrace();
result.setCode( 300 );
result.setMsg( "更新异常" );
}
return result;
}
@DeleteMapping("delete/{userId}")
public ResultInfo sayDel(@PathVariable Integer userId) {
ResultInfo result =new ResultInfo();
System.out.println( userId + "<<<" );
try {
userservice.removeUserById( userId );
} catch (ParamException ex) {
ex.printStackTrace();
result.setCode( ex.getCode() );
result.setMsg( ex.getMsg() );
}catch(Exception ex){
ex.printStackTrace();
result.setCode( 300 );
result.setMsg( "删除异常" );
}
return result;
}
@GetMapping("query")
public PageInfo<User> sayDel(UserQuery userQuery) {
ResultInfo result=new ResultInfo();
System.out.println( userQuery + "<<<" );
PageInfo<User> plist =userservice.queryUserByPage( userQuery );
return plist;
}
}
分页查询实现 需要定义对前端返回的对象进行的封装
public class UserQuery {
private Integer pageNum=1;
private Integer pageSize=1;
private String userName;
捕获全局异常
public class ParamException extends RuntimeException{
private Integer code=300;
private String msg="参数异常";
public class AssertUtil {
public static void isTrue(Boolean flag,String msg){
if(flag){
throw new ParamException(msg);
}
}
}
返回结果进行封装
public class ResultInfo {
private Integer code=200;
private String msg="操作成功";
private Object object;
最后在启动类上添加上mapper路径
@SpringBootApplication
@MapperScan("com.liuyang.mapper")
public class SpringbootcurdApplication {
|