仅做记录自己学习.
Hibernate
添加spring-boot-starter-jdbc依赖:
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-jpa
artifactId>
dependency>
添加mysql连接类和连接池类:
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
username: root
password: 123456
通过@Entity 表明是一个映射的实体类, @Id表明id, @GeneratedValue 字段自动生成
@Entity
public class Account {
@Id
@GeneratedValue
private int id ;
private String name ;
private double money;
... 省略getter setter
}
数据访问层,通过编写一个继承自 JpaRepository 的接口就能完成数据访问,其中包含了基本的单表查询的方法,非常的方便。值得注意的是,这个Account 对象名,而不是具体的表名,另外Interger是主键的类型,一般为Integer或者Long
public interface AccountDao extends JpaRepository<Account,Integer> {
}
在这个栗子中我简略了service层的书写,在实际开发中,不可省略。新写一个controller,写几个restful api来测试数据的访问。
@RestController
@RequestMapping("/account")
public class AccountController {
@Autowired
AccountDao accountDao;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public List getAccounts() {
return accountDao.findAll();
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Account getAccountById(@PathVariable("id") int id) {
return accountDao.findOne(id);
}
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public String updateAccount(@PathVariable("id") int id, @RequestParam(value = "name", required = true) String name,
@RequestParam(value = "money", required = true) double money) {
Account account = new Account();
account.setMoney(money);
account.setName(name);
account.setId(id);
Account account1 = accountDao.saveAndFlush(account);
return account1.toString();
}
@RequestMapping(value = "", method = RequestMethod.POST)
public String postAccount(@RequestParam(value = "name") String name,
@RequestParam(value = "money") double money) {
Account account = new Account();
account.setMoney(money);
account.setName(name);
Account account1 = accountDao.save(account);
return account1.toString();
}
}
几个注解解释:
@RestController与@Controller
@restcontroller是一个方便的注释,它只不过是添加了@controller和@respsebody注释
@PathVariable可以用来映射URL中的占位符到目标方法的参数中
@RequestParam可以轻松的将URL中的参数绑定到处理函数方法的变量中:类似?key=value1&key2=value2这样的参数列表。
需要添加mybatis-spring-boot-starter依赖跟mysql依赖
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.0
mysql
mysql-connector-java
这里不引入spring-boot-starter-jdbc依赖,是由于mybatis-spring-boot-starter中已经包含了此依赖。
mybatis-spring-boot-starter依赖将会提供如下:
就是说,使用了该Starter之后,只需要定义一个DataSource即可(application.properties中可配置),它会自动创建使用该DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。会自动扫描你的Mappers,连接到SqlSessionTemplate,并注册到Spring上下文中。
在src/main/resources/application.properties中配置数据源信息。
spring.datasource.url = jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
不管是注解方式还是XML配置的方式,以下代码模块都是一样的
public class LearnResouce {
private Long id;
private String author;
private String title;
private String url;
// SET和GET方法
}
@Controller
@RequestMapping("/learn")
public class LearnController {
@Autowired
private LearnService learnService;
private Logger logger = LoggerFactory.getLogger(this.getClass());
@RequestMapping("")
public String learn(){
return "learn-resource";
}
@RequestMapping(value = "/queryLeanList",method = RequestMethod.POST,produces="application/json;charset=UTF-8")
@ResponseBody
public void queryLearnList(HttpServletRequest request ,HttpServletResponse response){
String page = request.getParameter("page"); // 取得当前页数,注意这是jqgrid自身的参数
String rows = request.getParameter("rows"); // 取得每页显示行数,,注意这是jqgrid自身的参数
String author = request.getParameter("author");
String title = request.getParameter("title");
Map params = new HashMap();
params.put("page", page);
params.put("rows", rows);
params.put("author", author);
params.put("title", title);
List learnList=learnService.queryLearnResouceList(params);
PageInfo pageInfo =new PageInfo(learnList);
JSONObject jo=new JSONObject();
jo.put("rows", learnList);
jo.put("total", pageInfo.getPages());//总页数
jo.put("records",pageInfo.getTotal());//查询出的总记录数
ServletUtil.createSuccessResponse(200, jo, response);
}
/**
* 新添教程
* @param request
* @param response
*/
@RequestMapping(value = "/add",method = RequestMethod.POST)
public void addLearn(HttpServletRequest request , HttpServletResponse response){
JSONObject result=new JSONObject();
String author = request.getParameter("author");
String title = request.getParameter("title");
String url = request.getParameter("url");
if(StringUtil.isNull(author)){
result.put("message","作者不能为空!");
result.put("flag",false);
ServletUtil.createSuccessResponse(200, result, response);
return;
}
if(StringUtil.isNull(title)){
result.put("message","教程名称不能为空!");
result.put("flag",false);
ServletUtil.createSuccessResponse(200, result, response);
return;
}
if(StringUtil.isNull(url)){
result.put("message","地址不能为空!");
result.put("flag",false);
ServletUtil.createSuccessResponse(200, result, response);
return;
}
LearnResouce learnResouce = new LearnResouce();
learnResouce.setAuthor(author);
learnResouce.setTitle(title);
learnResouce.setUrl(url);
int index=learnService.add(learnResouce);
if(index>0){
result.put("message","教程信息添加成功!");
result.put("flag",true);
}else{
result.put("message","教程信息添加失败!");
result.put("flag",false);
}
ServletUtil.createSuccessResponse(200, result, response);
}
/**
* 修改教程
* @param request
* @param response
*/
@RequestMapping(value = "/update",method = RequestMethod.POST)
public void updateLearn(HttpServletRequest request , HttpServletResponse response){
JSONObject result=new JSONObject();
String id = request.getParameter("id");
LearnResouce learnResouce=learnService.queryLearnResouceById(Long.valueOf(id));
String author = request.getParameter("author");
String title = request.getParameter("title");
String url = request.getParameter("url");
if(StringUtil.isNull(author)){
result.put("message","作者不能为空!");
result.put("flag",false);
ServletUtil.createSuccessResponse(200, result, response);
return;
}
if(StringUtil.isNull(title)){
result.put("message","教程名称不能为空!");
result.put("flag",false);
ServletUtil.createSuccessResponse(200, result, response);
return;
}
if(StringUtil.isNull(url)){
result.put("message","地址不能为空!");
result.put("flag",false);
ServletUtil.createSuccessResponse(200, result, response);
return;
}
learnResouce.setAuthor(author);
learnResouce.setTitle(title);
learnResouce.setUrl(url);
int index=learnService.update(learnResouce);
System.out.println("修改结果="+index);
if(index>0){
result.put("message","教程信息修改成功!");
result.put("flag",true);
}else{
result.put("message","教程信息修改失败!");
result.put("flag",false);
}
ServletUtil.createSuccessResponse(200, result, response);
}
/**
* 删除教程
* @param request
* @param response
*/
@RequestMapping(value="/delete",method = RequestMethod.POST)
@ResponseBody
public void deleteUser(HttpServletRequest request ,HttpServletResponse response){
String ids = request.getParameter("ids");
System.out.println("ids==="+ids);
JSONObject result = new JSONObject();
//删除操作
int index = learnService.deleteByIds(ids.split(","));
if(index>0){
result.put("message","教程信息删除成功!");
result.put("flag",true);
}else{
result.put("message","教程信息删除失败!");
result.put("flag",false);
}
ServletUtil.createSuccessResponse(200, result, response);
}
}
package com.dudu.service;
public interface LearnService {
int add(LearnResouce learnResouce);
int update(LearnResouce learnResouce);
int deleteByIds(String[] ids);
LearnResouce queryLearnResouceById(Long learnResouce);
List queryLearnResouceList(Map params);
}
@Service
public class LearnServiceImpl implements LearnService {
@Autowired
LearnMapper learnMapper;
@Override
public int add(LearnResouce learnResouce) {
return this.learnMapper.add(learnResouce);
}
@Override
public int update(LearnResouce learnResouce) {
return this.learnMapper.update(learnResouce);
}
@Override
public int deleteByIds(String[] ids) {
return this.learnMapper.deleteByIds(ids);
}
@Override
public LearnResouce queryLearnResouceById(Long id) {
return this.learnMapper.queryLearnResouceById(id);
}
@Override
public List queryLearnResouceList(Map params) {
PageHelper.startPage(Integer.parseInt(params.get("page").toString()), Integer.parseInt(params.get("rows").toString()));
return this.learnMapper.queryLearnResouceList(params);
}
}
Mybatis注解的方式好简单,只要定义一个dao接口,然后sql语句通过注解写在接口方法上。最后给这个接口添加@Mapper注解或者在启动类上添加@MapperScan(“com.dudu.dao”)注解都行。
如下:
@Component
@Mapper
public interface LearnMapper {
@Insert("insert into learn_resource(author, title,url) values(#{author},#{title},#{url})")
int add(LearnResouce learnResouce);
@Update("update learn_resource set author=#{author},title=#{title},url=#{url} where id = #{id}")
int update(LearnResouce learnResouce);
@DeleteProvider(type = LearnSqlBuilder.class, method = "deleteByids")
int deleteByIds(@Param("ids") String[] ids);
@Select("select * from learn_resource where id = #{id}")
@Results(id = "learnMap", value = {
@Result(column = "id", property = "id", javaType = Long.class),
@Result(property = "author", column = "author", javaType = String.class),
@Result(property = "title", column = "title", javaType = String.class)
})
LearnResouce queryLearnResouceById(@Param("id") Long id);
@SelectProvider(type = LearnSqlBuilder.class, method = "queryLearnResouceByParams")
List queryLearnResouceList(Map params);
class LearnSqlBuilder {
public String queryLearnResouceByParams(final Map params) {
StringBuffer sql =new StringBuffer();
sql.append("select * from learn_resource where 1=1");
if(!StringUtil.isNull((String)params.get("author"))){
sql.append(" and author like '%").append((String)params.get("author")).append("%'");
}
if(!StringUtil.isNull((String)params.get("title"))){
sql.append(" and title like '%").append((String)params.get("title")).append("%'");
}
System.out.println("查询sql=="+sql.toString());
return sql.toString();
}
//删除的方法
public String deleteByids(@Param("ids") final String[] ids){
StringBuffer sql =new StringBuffer();
sql.append("DELETE FROM learn_resource WHERE id in(");
for (int i=0;i
需要注意的是,简单的语句只需要使用@Insert、@Update、@Delete、@Select这4个注解即可,但是有些复杂点需要动态SQL语句,就比如上面方法中根据查询条件是否有值来动态添加sql的,就需要使用@InsertProvider、@UpdateProvider、@DeleteProvider、@SelectProvider等注解。
这些可选的 SQL 注解允许你指定一个类名和一个方法在执行时来返回运行 允许创建动态 的 SQL。 基于执行的映射语句, MyBatis 会实例化这个类,然后执行由 provider 指定的方法. 该方法可以有选择地接受参数对象.(In MyBatis 3.4 or later, it’s allow multiple parameters) 属性: type,method。type 属性是类。method 属性是方法名。 注意: 这节之后是对 类的 讨论,它可以帮助你以干净,容于阅读 的方式来构建动态 SQL。
xml配置方式保持映射文件的老传统,优化主要体现在不需要实现dao的是实现层,系统会自动根据方法名在映射文件中找对应的sql,具体操作如下:
编写Dao层的代码
新建LearnMapper接口,无需具体实现类。
@Mapper
public interface LearnMapper {
int add(LearnResouce learnResouce);
int update(LearnResouce learnResouce);
int deleteByIds(String[] ids);
LearnResouce queryLearnResouceById(Long id);
public List queryLearnResouceList(Map params);
}
修改application.properties 配置文件
#指定bean所在包
mybatis.type-aliases-package=com.dudu.domain
#指定映射文件
mybatis.mapperLocations=classpath:mapper/*.xml
添加LearnMapper的映射文件
在src/main/resources目录下新建一个mapper目录,在mapper目录下新建LearnMapper.xml文件。
通过mapper标签中的namespace属性指定对应的dao映射,这里指向LearnMapper。
id, author, title,url
INSERT INTO learn_resource (author, title,url) VALUES (#{author}, #{title}, #{url})
UPDATE learn_resource SET author = #{author},title = #{title},url = #{url} WHERE id = #{id}
DELETE FROM learn_resource WHERE id in
#{idItem}
resultMap包含的元素:
<resultMap id="唯一的标识" type="映射的pojo对象">
<id column="表的主键字段,或者可以为查询语句中的别名字段" jdbcType="字段类型" property="映射pojo对象的主键属性" />
<result column="表的一个字段(可以为任意表的一个字段)" jdbcType="字段类型" property="映射到pojo对象的一个属性(须为type定义的pojo对象中的一个属性)"/>
<association property="pojo的一个对象属性" javaType="pojo关联的pojo对象">
<id column="关联pojo对象对应表的主键字段" jdbcType="字段类型" property="关联pojo对象的主席属性"/>
<result column="任意表的字段" jdbcType="字段类型" property="关联pojo对象的属性"/>
association>
<collection property="pojo的集合属性" ofType="集合中的pojo对象">
<id column="集合中pojo对象对应的表的主键字段" jdbcType="字段类型" property="集合中pojo对象的主键属性" />
<result column="可以为任意表的字段" jdbcType="字段类型" property="集合中的pojo对象的属性" />
collection>
resultMap>
如果collection标签是使用嵌套查询,格式如下:
pom.xml中添加依赖
com.github.pagehelper
pagehelper-spring-boot-starter
1.1.0
然后你只需在查询list之前使用PageHelper.startPage(int pageNum, int pageSize)方法即可。pageNum是第几页,pageSize是每页多少条。
@Override
public List queryLearnResouceList(Map params) {
PageHelper.startPage(Integer.parseInt(params.get("page").toString()), Integer.parseInt(params.get("rows").toString()));
return this.learnMapper.queryLearnResouceList(params);
}
http://blog.csdn.net/forezp/article/details/70545038
http://tengj.top/2017/04/23/springboot9/
https://www.cnblogs.com/kenhome/p/7764398.html