天天看點

Springboot+MyBatis——通用Mapper

1,建立一個Maven項目,并配置成Springboot架構+MyBatis持久層+druid連接配接池+MySQL資料庫

2,添加通用Mapper的依賴

<dependency>
        <groupId>tk.mybatis</groupId>
        <artifactId>mapper-spring-boot-starter</artifactId>//SpringBoot項目中添加該依賴
        <version>1.2.3</version>
    </dependency>
           
<dependency>
	<groupId>tk.mybatis</groupId>
	<artifactId>mapper</artifactId>//正常項目
	<version>4.0.0</version>
</dependency>
           

3,新增一個接口繼承Mapper,MysqlMapper接口

public interface MyMapper<T> extends Mapper<T>,MySqlMapper<T>{
}
           

4,編寫實體類,并在類名添加 @table注解,成員變量添加 @Column注解

@Table(name="studentinfo")//name為表名
public class Student {
	@Column(name="stuno")//name為字段名
	private Integer stuno;
	@Column(name="stuname")
	private String stuname;
	@Column(name="stubirth")
	private Date stubirth;
	@Column(name="stusex")
	private Integer stusex;
	@Column(name="stuaddr")
	private String stuaddr;
	@Column(name="stutel")
	private String stutel;
	public Integer getStuno() {
		return stuno;
	}
	public void setStuno(Integer stuno) {
		this.stuno = stuno;
	}
	public String getStuname() {
		return stuname;
	}
	public void setStuname(String stuname) {
		this.stuname = stuname;
	}
	public Date getStubirth() {
		return stubirth;
	}
	public void setStubirth(Date stubirth) {
		this.stubirth = stubirth;
	}
	public Integer getStusex() {
		return stusex;
	}
	public void setStusex(Integer stusex) {
		this.stusex = stusex;
	}
	public String getStuaddr() {
		return stuaddr;
	}
	public void setStuaddr(String stuaddr) {
		this.stuaddr = stuaddr;
	}
	public String getStutel() {
		return stutel;
	}
	public void setStutel(String stutel) {
		this.stutel = stutel;
	}
	@Override
	public String toString() {
		return "Student [stuno=" + stuno + ", stuname=" + stuname + ", stubirth=" + stubirth + ", stusex=" + stusex
				+ ", stuaddr=" + stuaddr + ", stutel=" + stutel + "]";
	}
}
           

5,編寫對應的接口類實作自定義的Mapper類,并加上Mapper注解

@Mapper
public interface TestMapper extends MyMapper<Student>{
}
           

6,使用Service去調用

@Service
public class TestService {
	@Autowired
	TestMapper testMapper;
	public Object queryAllStudents() {
		return testMapper.selectAll();
	}
}
           

7,使用控制器元件去調用Service元件

@Controller
public class TestController {
	Logger logger=LoggerFactory.getLogger(getClass());

	@Autowired
	TestService testService;

	@RequestMapping("a")
	@ResponseBody
	public String test1() {
		String str=JSON.toJSONString(testService.queryAllStudents());
		logger.info(str);
		return str;
	}
}
           

8,在浏覽器中進行調用

繼續閱讀