通用Mapper快速開(kāi)發(fā),搭建項(xiàng)目
搭建環(huán)境
配置maven依賴的架包
?
????????
????????????tk.mybatis
????????????mapper
????????????4.0.0-beta3
????????
????????
????????????junit
????????????junit
????????????4.9
????????
????????
????????????log4j
????????????log4j
????????????1.2.17
????????
????????
????????????cglib
????????????cglib
????????????2.2
????????
????????
????????????org.aspectj
????????????aspectjweaver
????????????1.6.8
????????
????????
????????????org.slf4j
????????????slf4j-api
????????????1.7.7
????????
????????
????????????org.slf4j
????????????slf4j-log4j12
????????????1.7.7
????????
????????
????????????org.mybatis
????????????mybatis
????????????3.2.8
????????
????????
????????????org.mybatis
????????????mybatis-spring
????????????1.2.2
????????
????????
????????????com.mchange
????????????c3p0
????????????0.9.2
????????
????????
????????????org.springframework
????????????spring-context
????????????4.3.10.RELEASE
????????
????????
????????????mysql
????????????mysql-connector-java
????????????5.1.37
????????
????????
????????????org.springframework
????????????spring-orm
????????????4.3.10.RELEASE
????????
????
Spring整合mybatis
"1.0"?encoding="UTF-8"?>
"-//mybatis.org//DTD?Config?3.0//EN"?"http://mybatis.org/dtd/mybatis-3-config.dtd">
Spring的配置文件
"1.0"?encoding="UTF-8"?>
"http://www.springframework.org/schema/beans"
?xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
?xmlns:aop="http://www.springframework.org/schema/aop"
?xmlns:context="http://www.springframework.org/schema/context"
?xmlns:tx="http://www.springframework.org/schema/tx"
?xsi:schemaLocation="http://www.springframework.org/schema/beans?http://www.springframework.org/schema/beans/spring-beans.xsd
??http://www.springframework.org/schema/context?http://www.springframework.org/schema/context/spring-context-4.3.xsd
??http://www.springframework.org/schema/aop?http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
??http://www.springframework.org/schema/tx?http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
?
?"classpath:jdbc.properties"/>
?"dataSource"?class="com.mchange.v2.c3p0.ComboPooledDataSource">
??"user"?value="${jdbc.user}"/>
??"password"?value="${jdbc.password}"/>
??"jdbcUrl"?value="${jdbc.url}"/>
??"driverClass"?value="${jdbc.driver}"/>
?
?
?"sqlSessionFactoryBean"?class="org.mybatis.spring.SqlSessionFactoryBean">
??"configLocation"?value="classpath:mybatis-config.xml"/>
??"dataSource"?ref="dataSource"/>
?
?
?
?
?
?class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
??"basePackage"?value="com.yang.mapper.mappers"/>
?
?
?package="com.yang.mapper.services"/>
?
?"dataSourceTransactionManager"?class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
??"dataSource"?ref="dataSource"/>
?
?
??"txAdvice"?pointcut="execution(*?*..*Service.*(..))"/>
?
?"txAdvice"?transaction-manager="dataSourceTransactionManager">
??
???"get*"?read-only="true"/>
???"save*"?rollback-for="java.lang.Exception"?propagation="REQUIRES_NEW"/>
???"remove*"?rollback-for="java.lang.Exception"?propagation="REQUIRES_NEW"/>
???"update*"?rollback-for="java.lang.Exception"?propagation="REQUIRES_NEW"/>
??
?
整合log4j.properties配置文件
log4j.rootLogger=DEBUG,myConsole
log4j.appender.myConsole=org.apache.log4j.ConsoleAppender
log4j.appender.myConsole.ImmediateFlush=true
log4j.appender.myConsole.Target=System.out
log4j.appender.myConsole.layout=org.apache.log4j.PatternLayout
log4j.appender.myConsole.layout.ConversionPattern=[%-5p]?%d(%r)?-->?[%t]?%l:?%m?%x?%n
log4j.logger.com.mchange.v2=ERROR
數(shù)據(jù)庫(kù)jdbc.properties配置文件
jdbc.user=root
jdbc.password=root
jdbc.url=jdbc:mysql://localhost:3306/girls?useUnicode=true&characterEncoding=utf8
jdbc.driver=com.mysql.jdbc.Driver
數(shù)據(jù)庫(kù)表的設(shè)計(jì)
CREATE?TABLE?`tabple_emp`?(
`emp_id`?int?NOT?NULL?AUTO_INCREMENT?,?
`emp_name`?varchar(500)?NULL?,
`emp_salary`?double(15,5)?NULL?,
`emp_age`?int?NULL?,?PRIMARY?KEY?(`emp_id`)?
);
INSERT?INTO?`tabple_emp`?(`emp_name`,?`emp_salary`,?`emp_age`)?VALUES?('tom',?'1254.37',?'27');
INSERT?INTO?`tabple_emp`?(`emp_name`,?`emp_salary`,?`emp_age`)?VALUES?('jerry',?'6635.42',?'38');?
INSERT?INTO?`tabple_emp`?(`emp_name`,?`emp_salary`,?`emp_age`)?VALUES?('bob',?'5560.11',?'40');?
INSERT?INTO?`tabple_emp`?(`emp_name`,?`emp_salary`,?`emp_age`)?VALUES?('kate',?'2209.11',?'22');
INSERT?INTO?`tabple_emp`?(`emp_name`,?`emp_salary`,?`emp_age`)?VALUES?('justin',?'4203.15',?'30');
建立實(shí)體類
@Table(name?=?"tabple_emp")
public?class?Employee?{
?????//???@Transient當(dāng)數(shù)據(jù)庫(kù)里面沒(méi)有某個(gè)字段的時(shí)候可以用此注解
????private?Integer?empId;
????//????當(dāng)數(shù)據(jù)字段和實(shí)體類字段不一致時(shí)可以用該字段
????@Column(name?=?"emp_name")
????private?String?empName;
????private?Double?empSalary;
????private?Integer?empAge;
????get,set方法省略.......
????}
建立mapper的dao層
package?com.yang.mapper.dao;
import?com.yang.mapper.entity.Employee;
import?tk.mybatis.mapper.common.Mapper;
/**
?*?繼承Mapper<實(shí)體類
?*
?*/
public?interface?EmployeeMapper?extends?Mapper<Employee>?{
}
簡(jiǎn)單的測(cè)試
package?com.yang.mapper.services;
import?com.yang.mapper.entity.Employee;
import?org.apache.ibatis.session.RowBounds;
import?org.junit.Test;
import?org.springframework.context.ApplicationContext;
import?org.springframework.context.support.ClassPathXmlApplicationContext;
import?tk.mybatis.mapper.entity.Example;
import?java.util.List;
import?static?org.junit.Assert.*;
public?class?EmployeeServiceTest?{
????private?ApplicationContext?iocContainer?=?new?ClassPathXmlApplicationContext("spring-context.xml");
????private?EmployeeService?employeeService?=?iocContainer.getBean(EmployeeService.class);
????@Test
????public?void?testSelectOne()?{
????????//1.創(chuàng)建封裝查詢條件的實(shí)體類對(duì)象
????????Employee?employeeQueryCondition?=?new?Employee(null,?"bob",?5560.11,?null);
????????//2.執(zhí)行查詢
????????Employee?employeeQueryResult?=?employeeService.getOne(employeeQueryCondition);
????????//3.打印
????????System.out.println(employeeQueryResult);
????}
????@Test
????public?void?testSelectByPrimaryKey()?{
????????//1.提供id值
????????Integer?empId?=?3;
????????//2.執(zhí)行根據(jù)主鍵進(jìn)行的查詢
????????Employee?employee?=?employeeService.getEmployeeById(empId);
????????//3.打印結(jié)果
????????System.out.println(employee);
????}
????@Test
????public?void?testExistsWithPrimaryKey()?{
????????//1.提供主鍵值
????????Integer?empId?=?33;
????????//2.執(zhí)行查詢
????????boolean?exists?=?employeeService.isExists(empId);
????????//3.打印結(jié)果
????????System.out.println(exists);
????}
????@Test
????public?void?testInsert()?{
????????//1.創(chuàng)建實(shí)體類對(duì)象封裝要保存到數(shù)據(jù)庫(kù)的數(shù)據(jù)
????????Employee?employee?=?new?Employee(null,?"emp03",?3000.00,?23);
????????//2.執(zhí)行插入操作
????????employeeService.saveEmployee(employee);
????????//3.獲取employee對(duì)象的主鍵字段值
????????Integer?empId?=?employee.getEmpId();
????????System.out.println("empId="+empId);
????}
????@Test
????public?void?testInsertSelective()?{
????????//1.創(chuàng)建實(shí)體類對(duì)象封裝要保存到數(shù)據(jù)庫(kù)的數(shù)據(jù)
????????Employee?employee?=?new?Employee(null,?"emp04",?null,?23);
????????//2.執(zhí)行插入操作
????????employeeService.saveEmployeeSelective(employee);
????}
????@Test
????public?void?testUpdateByPrimaryKeySelective()?{
????????//1.創(chuàng)建用于測(cè)試的實(shí)體類
????????Employee?employee?=?new?Employee(7,?"empNewName",?null,?null);
????????//2.執(zhí)行更新
????????employeeService.updateEmployeeSelective(employee);
????}
????@Test
????public?void?testDelete()?{
????????//1.聲明實(shí)體類變量作為查詢條件
????????Employee?employee?=?null;
????????//2.執(zhí)行刪除
????????employeeService.removeEmployee(employee);
????}
????@Test
????public?void?testDeleteByPrimaryKey()?{
????????//1.提供主鍵值
????????Integer?empId?=?13;
????????//2.執(zhí)行刪除
????????employeeService.removeEmployeeById(empId);
????}
????@Test
????public?void?testSelectByExample()?{
????????//目標(biāo):WHERE (emp_salary>? AND emp_age) OR (emp_salary AND emp_age>?)
????????//1.創(chuàng)建Example對(duì)象
????????Example?example?=?new?Example(Employee.class);
????????//***********************
????????//i.設(shè)置排序信息
????????example.orderBy("empSalary").asc().orderBy("empAge").desc();
????????//ii.設(shè)置“去重”
????????example.setDistinct(true);
????????//iii.設(shè)置select字段
????????example.selectProperties("empName","empSalary");
????????//***********************
????????//2.通過(guò)Example對(duì)象創(chuàng)建Criteria對(duì)象
????????Example.Criteria?criteria01?=?example.createCriteria();
????????Example.Criteria?criteria02?=?example.createCriteria();
????????//3.在兩個(gè)Criteria對(duì)象中分別設(shè)置查詢條件
????????//property參數(shù):實(shí)體類的屬性名
????????//value參數(shù):實(shí)體類的屬性值
????????criteria01.andGreaterThan("empSalary",?3000)
????????????????.andLessThan("empAge",?25);
????????criteria02.andLessThan("empSalary",?5000)
????????????????.andGreaterThan("empAge",?30);
????????//4.使用OR關(guān)鍵詞組裝兩個(gè)Criteria對(duì)象
????????example.or(criteria02);
????????//5.執(zhí)行查詢
????????List?empList?=?employeeService.getEmpListByExample(example);
????????for?(Employee?employee?:?empList)?{
????????????System.out.println(employee);
????????}
????}
????@Test
????public?void?testSelectByRowBounds()?{
????????int?pageNo?=?3;
????????int?pageSize?=?5;
????????int?index?=?(pageNo?-?1)?*?pageSize;
????????RowBounds?rowBounds?=?new?RowBounds(index,?pageSize);
????????List?empList?=?employeeService.getEmpListByRowBounds(rowBounds);
????????for?(Employee?employee?:?empList)?{
????????????System.out.println(employee);
????????}
????}
}

當(dāng)數(shù)據(jù)庫(kù)為空時(shí)可以加個(gè)注解@Id
package?com.yang.mapper.entity;
import?javax.persistence.Column;
import?javax.persistence.Id;
import?javax.persistence.Table;
//指定數(shù)據(jù)庫(kù)表名
@Table(name?=?"tabple_emp")
public?class?Employee?{
????@Id
????@GeneratedValue(strategy?=?GenerationType.IDENTITY)
????private?Integer?empId;
????private?Integer?empId;
//????當(dāng)數(shù)據(jù)字段和實(shí)體類字段不一致時(shí)可以用該字段
????@Column(name?=?"emp_name")
????private?String?empName;
????private?Double?empSalary;
????private?Integer?empAge;

評(píng)論
圖片
表情
