tkMaper通用Mapper详细使用,可以不用你在写sql语句
Posted SmallCuteMonkey
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了tkMaper通用Mapper详细使用,可以不用你在写sql语句相关的知识,希望对你有一定的参考价值。
tkMapper使用 通用Mapper使用
需要提前的添加Mybatis的依赖,因为tkMapper是基于Mybatis框架的
1.1添加依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!--tkMapper的使用-->
<dependencies>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.0.4</version>
</dependency>
<!-- mybaits-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
</dependencies>
1.2增加启动类的注解@MapperScan tk.mybatis.spring.annotation.MapperScan;
package com.hou;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
@MapperScan("com.hou.dao")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
1.3创建实体类
如果类名和表名一致可以不用加上@Table, @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)这个是主键自增的生成策略。@Column(name="") 可以和数据库的字段进行配置
package com.hou.pojo;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
import java.util.List;
@Data
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Integer id;
String username;
String password;
@DateTimeFormat(pattern = "yyyy-MM-dd")
Date Birthday;
List<Orders> ordersList;
}
package com.hou.pojo;
import lombok.Data;
@Data
public class Orders {
private Integer orderId;
private Integer userId;
private String receiverName;
private String receiver_address;
private String totalAmount;
}
package com.hou.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Category {
@Id
// 可以使用主键自增策略
@GeneratedValue(strategy = GenerationType.IDENTITY)
// 这个属性可以和数据库的字段相匹配
@Column(name = "category_id")
private int categoryId;
private String categoryName;
@Column(name = "category_level")
private int categoryLevel;
private int categoryIcon;
private String categorySlogan;
private String categoryPic;
private String categoryBgColor;
}
结构图:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5aEljDWA-1628601985575)(C:\\Users\\CourageAndLove\\AppData\\Roaming\\Typora\\typora-user-images\\image-20210810211120647.png)]
1.4创建Dao接口
package com.hou.dao;
import com.hou.general.GeneralDao;
import com.hou.pojo.Category;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
public interface CategoryDao extends GeneralDao<Category> {
}
package com.hou.dao;
import com.hou.general.GeneralDao;
import com.hou.pojo.Orders;
import tk.mybatis.mapper.common.Mapper;
public interface OrderDao extends GeneralDao<Orders> {
}
package com.hou.dao;
import com.hou.general.GeneralDao;
import com.hou.pojo.User;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
public interface UserDao extends GeneralDao<User> {
// 自定义查询
User queryByUserName(String username);
}
package com.hou.general;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
public interface GeneralDao<T> extends Mapper<T>, MySqlMapper<T> {
}
1.5通过Example进行查询
注意criteria.andEqualto(Property,value),和orEqualto(Property,value)的区别 andLike(类的属性名,"%mohu%")和orLike(类的属性名,value)的区别
package com.hou.controller;
import com.hou.dao.CategoryDao;
import com.hou.pojo.Category;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;
import java.util.List;
@Controller
@ResponseBody
public class CategoryController {
@Autowired
CategoryDao categoryDao;
/*
@RequestMapping("listcategory")
public List<Category> list(){
Category category=new Category();
category.setCategoryName("家具");
category.setCategoryBgColor("black");
category.setCategoryLevel(1);
category.setCategoryIcon(2);
category.setCategoryPic("img/1.jpg");
category.setCategorySlogan("hahah");
// categoryDao.insert(category);
categoryDao.insertUseGeneratedKeys(category);
List<Category> categories = categoryDao.selectAll();
return categories;
}
@RequestMapping("updateCategory")
public int totestUpate(){
Category category=new Category();
category.setCategoryId(1);
category.setCategoryName("水果");
category.setCategoryBgColor("black");
category.setCategoryLevel(1);
category.setCategoryIcon(2);
category.setCategoryPic("img/1.jpg");
category.setCategorySlogan("hahah");
int i = categoryDao.updateByPrimaryKey(category);
System.out.println(i);
return i;
}
@RequestMapping("deletcategory")
public int delete(){
int i = categoryDao.deleteByPrimaryKey(1);
return i;
}
*/
// 使用Example例子进行相关的增删改查
@RequestMapping("selectByExample")
public List<Category> selectByExample(){
Example example=new Example(Category.class);
Example.Criteria criteria = example.createCriteria();
// property为类的属性值,value加上类的条件
// 查询等级为1的category
criteria.andEqualTo("categoryLevel",1);
// 查询等级或者为2
criteria.orEqualTo("categoryLevel",2);
List<Category> categorielist = categoryDao.selectByExample(example);
return categorielist;
}
@RequestMapping("selectByExample1")
public List<Category> selectByExample1(){
Example example=new Example(Category.class);
Example.Criteria criteria = example.createCriteria();
// property为类的属性值,value加上类的条件
// 进行模糊查询
// 用and进行连接的必须满足这个两个条件的查询
criteria.andEqualTo("categoryLevel",1);
criteria.andLike("categoryName","%果%");
criteria.orLike("categoryName","%家%");
List<Category> categorielist = categoryDao.selectByExample(example);
return categorielist;
}
// 进行分页查询
@RequestMapping("selectByExamplePage")
public List<Category> selectByExamplePage(){
int pageNum=1;
int pageSize=2;
//从第几条开始查询
int start= (pageNum-1)*pageSize;
RowBounds rowBounds=new RowBounds(start,pageSize);
List<Category> list = categoryDao.selectByRowBounds(new Category(), rowBounds);
// 查询总记录数
int i = categoryDao.selectCount(new Category());
System.out.println(i);
return list;
}
}
1.6通过selectByRowBounds(new Category(), rowBounds)进行分页的查询
// 进行分页查询
@RequestMapping("selectByExamplePage")
public List<Category> selectByExamplePage(){
int pageNum=1;
int pageSize=2;
//从第几条开始查询
int start= (pageNum-1)*pageSize;
RowBounds rowBounds=new RowBounds(start,pageSize);
List<Category> list = categoryDao.selectByRowBounds(new Category(), rowBounds);
// 查询总记录数
int i = categoryDao.selectCount(new Category());
System.out.println(i);
return list;
}
1.7通过selectByExampleAndRowBounds(example,rowBounds)进行条件分页查询
// 进行条件和分页查询 selectByExampleAndRowBounds()
@RequestMapping("selectByExampleAndRowBounds")
public List<Category> select(){
// 带上条件的分页,需要先满足条件然后再进行分页
Example example=new Example(Category.class);
Example.Criteria criteria = example.createCriteria();
criteria.andEqualTo("categoryLevel",1);
int pageNum=1;
int pageSize=2;
int start=(pageNum-1)*pageSize;
RowBounds rowBounds=new RowBounds(start,pageSize);
List<Category> list = categoryDao.selectByExampleAndRowBounds(example, rowBounds);
int i = categoryDao.selectCountByExample(example);
System.out.println(i);
return list;
}
1.8通用mapper自定义的查询
直接在UserDao中写上自定义的方法
-
在resources下面建立mapper目录,下面建立相应的文件UserMapper.xml
-
需要在application.yml中的mybatis的mapper-location的相应的配置不要写错
mybatis: type-aliases-package: com.hou.pojo mapper-locations: classpath:mapper/*Mapper.xml
3.UserMapper.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.hou.dao.UserDao">
<resultMap id="userResultMap" type="User">
<id property="id" column="id"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
<collection property="ordersList" ofType="Orders" resultMap="orderResultMap"/>
</resultMap>
<resultMap id="orderResultMap" type="Orders">
<id property="orderId" column="order_id"/>
<result property="userId" column="user_id"/>
<result property="receiverName" column="receiver_name"/>
<result property="totalAmount" column="total_amount"/>
</resultMap>
<select id="queryByUserName" resultMap="userResultMap" parameterType="java.lang.String" >
select *from user u,orders o where u.id=o.user_id and username=#{username};
</select>
</mapper>
1.9测试文件RestController进行相关的测试,用Json数据回显到前端
package com.hou.controller;
import com.hou.dao.OrderDao;
import com.hou.dao.UserDao;
import com.hou.pojo.Orders;
import com.hou.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;
import java.util.List;
@RestController
public class UserController {
@Autowired
UserDao userDao;
@Autowired
private OrderDao orderDao;
@RequestMapping("queryOrdersByUserName")
public List<Orders> OneToMany(){
Example example = new Example(User.class);
Example.Criteria criteria = example.createCriteria();
criteria.andEqualTo("username","侯芳");
// 1.根据用户名查询到users
List<User> users = userDao.selectByExample(example);
User user = users.get(0);//因为知道username只有一个
// 2.根据users查询到userId,然后在Orders中进行查询订单的信息
Example example1 = new Example(Orders.class);
Example.Criteria criteria1 = example1.createCriteria();
criteria1.andEqualTo("userId",user.getId());
List<Orders> orders = orderDao.selectByExample(example1);
// 3.将查询到的orders放入User中
user.setOrdersList(orders);
// 4. 打印user
System.out.println(user);
return orders;
}
// 自定义的查询
@RequestMapping("queryByMyself")
public User queryByMyself(){
User user = userDao.queryByUserName("admin");
return user;
}
}
package com.hou.controller;
import com.hou.dao.CategoryDao;
import com.hou.pojo.Category;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;
import java.util.List;
@Controller
@ResponseBody
public class CategoryController {
@Autowired
CategoryDao categoryDao;
/*
@RequestMapping("listcategory")
public List<Category> list(){
Category category=new Category();
category.setCategoryName("家具");
category.setCategoryBgColor("black");
category.setCategoryLevel(1);
category.setCategoryIcon(2);
category.setCategoryPic("img/1.jpg");
category.setCategorySlogan("hahah");
// categoryDao.insert(category);
categoryDao.insertUseGeneratedKeys(category);
List<Category> categories = categoryDao.selectAll();
return categories;
}
@RequestMapping("updateCategory")
public int totestUpate(){
Category category=new Category();
category.setCategoryId(1);
category.setCategoryName("水果");
category.setCategoryBgColor("black");
category.setCategoryLevel(1);
category.setCategoryIcon(2);
category.setCategoryPic("img/1.jpg");
category.setCategorySlogan("hahah");
int i = categoryDao.updateByPrimaryKey(category);
System.out.println(i);
return i;
}
@RequestMapping("deletcategory")
public int delete(){
int i = categoryDao.deleteByPrimaryKey(1);
return i;
}
*/
// 使用Example例子进行相关的增删改查
@RequestMapping("selectByExample")
public List<Category> selectByExample(){
Example example=new Example(Category.class);
Example.Criteria criteria = example.createCriteria();
// property为类的属性值,value加上类的条件
// 查询等级为1的category
criteria.andEqualTo("categoryLevel",1);
// 查询等级或者为2
criteria.orEqualTo("categoryLevel",2);
List<Category> categorielist = categoryDao.selectByExample(example);
return categorielist;
}
@RequestMapping("selectByExample1")
public List<Category> selectByExample1(){
Example example=new Example(Category.class);
Example.Criteria criteria = example.createCriteria();
// property为类的属性值,value加上类的条件
// 进行模糊查询
// 用and进行连接的必须满足这个两个条件的查询
criteria.andEqualTo("categoryLevel",1);
criteria.andLike("categoryName","%果%");
criteria.orLike("categoryName","%家%");
List<Category> categorielist = categoryDao.selectByExample(example);
return categorielist;
}
// 进行分页查询
@RequestMapping("selectByExamplePage")
public List<Category> selectByExamplePage(){
int pageNum=1;
int pageSize=2;
//从第几条开始查询
int start= (pageNum-1)*pageSize;
RowBounds rowBounds=new RowBounds(start,pageSize);
List<Category> list = categoryDao.selectByRowBounds(new Category(), rowBounds);
// 查询总记录数
int i = categoryDao.selectCount(new Category());
System.out.println(i);
return list;
}
// 进行条件和分页查询 selectByExampleAndRowBounds()
@RequestMapping("selectByExampleAndRowBounds")
public List<Category> select(){
// 带上条件的分页,需要先满足条件然后再进行分页
Example example=new Example(Category.class);
Example.Criteria criteria = example.createCriteria();
criteria.andEqualTo("categoryLevel",1);
int pageNum=1;
int pageSize=2;
int start=(pageNum-1)*pageSize;
RowBounds rowBounds=new RowBounds(start,pageSize);
List<Category> list = categoryDao.selectByExampleAndRowBounds(example, rowBounds);
int i = categoryDao.selectCountByExample(example);
System.out.println(i);
return list;
}
}
以上是关于tkMaper通用Mapper详细使用,可以不用你在写sql语句的主要内容,如果未能解决你的问题,请参考以下文章