上次已经为大家介绍过java spring boot中怎么加入依赖的主要内容了。今天再为大家介绍一些与之相关的内容,也就是java spring
boot中怎么 编写mapper以及怎么编写service和controller?一起来了解一下吧。
首先说一下,java spring boot中怎么编写mapper?
代码如下所示:
import java.util.List; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import cn.cnn.info.pojo.User; //extends com.github.abel533.mapper.Mapper<User>:需要继承通用Mapper @Mapper public interface UserMapper extends com.github.abel533.mapper.Mapper < User > { @Select("select * from user where name like '%${value}%'") public List < User > queryUserByName(String name); // 使用UserMapper.xml配置文件 public List < User > queryAll(); }
然后说一下怎么编写service和controller?
Service编写,代码如下所示:
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.github.pagehelper.PageHelper; import cn.cnn.info.dao.UserDao; import cn.cnn.info.dao.UserMapper; import cn.cnn.info.pojo.User; import cn.cnn.info.service.UserService; @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Autowired private UserMapper userMapper; @Override public List < User > findAll() { List < User > list = this.userDao.findAll(); return list; } @Override public List < User > queryUserByName(String name) { List < User > list = this.userMapper.queryUserByName(name); return list; } // 调用使用UserMapper.xml的Mapper @Override public List < User > queryAll() { List < User > list = this.userMapper.queryAll(); return list; } // 使用通用Mapper和分页助手 @Override public List < User > queryUserByPage(Integer page, Integer rows) { // 设置分页 PageHelper.startPage(page, rows); // 使用通用Mapper的方法进行查询所有数据 List < User > list = this.userMapper.select(null); return list; } }
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.RestController; import cn.cnn.info.pojo.User; import cn.cnn.info.service.UserService; @RestController @RequestMapping("user") public class UserControlelr { @Autowired private UserService userService; @RequestMapping("list") public List < User > queryUserAll() { List < User > list = this.userService.findAll(); return list; } @RequestMapping("list/{name}") public List < User > queryUserAll(@PathVariable String name) { List < User > list = this.userService.queryUserByName(name); return list; } @RequestMapping("list/query") public List < User > queryUserAll2() { List < User > list = this.userService.queryAll(); return list; } @RequestMapping("list/{page}/{rows}") public List < User > queryUserAll(@PathVariable Integer page, @PathVariable Integer rows) { List < User > list = this.userService.queryUserByPage(page, rows); return list; } }
以上就是关于java spring boot中怎么 编写mapper以及怎么编写service和controller的主要内容了。具体的内容还是比较简单易懂的。如果你对java知识感兴趣,想要了解更多java实例和常见问题,敬请关注奇Q工具网。
推荐阅读: