第一種:
1.引入POM坐標,需要同時引入通用mapper和jpa
<dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <!-- 建議使用最新版本,最新版本請從項目首頁查找 --> <version>3.4.0</version> </dependency> <dependency> <groupId>javax.persistence</groupId> <artifactId>persistence-api</artifactId> <version>1.0</version> </dependency>
2.將自己的mapper文件繼承通用mapper的BaseMapper
@Repository public interface RatWaiterHitRewardMapper extends BaseMapper<RatWaiterHitReward>{ }
3.編寫JAVA BEAN配置類
@Configuration public class TkMybatisConfig { @Bean(name="mapperHelper") public MapperScannerConfigurer mapperHelper(){ Properties properties = new Properties(); properties.setProperty("mappers",BaseMapper.class.getName()); properties.setProperty("IDENTITY","MYSQL"); // 數據庫方言(主要用於:取回主鍵的方式) properties.setProperty("notEmpty","false"); // insert和update中,是否判斷字符串類型!='',少數方法會用到 properties.setProperty("style", Style.camelhump.name()); MapperScannerConfigurer scan = new MapperScannerConfigurer(); scan.setSqlSessionFactoryBeanName("sqlSessionFactory"); // 多數據源時,必須配置 scan.setBasePackage("com.eparty.ccp.rate.mapper");//mapper.java文件的路徑 scan.setMarkerInterface(BaseMapper.class); // 直接繼承了BaseDao接口的才會被掃描,basePackage可以配置的范圍更大。 scan.setProperties(properties); return scan; } }
第二種(推薦):
1、配置mybatis
application.properties(配置文件)
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&rewriteBatchedStatements=false&autoReconnect=true spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver # 指向mapper的xml文件位置 mybatis.mapper-locations=classpath*:mapper/*Mapper.xml
2、引入依賴(springboot專用)
<dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>RELEASE</version> </dependency>
3、配置啟動類
import tk.mybatis.spring.annotation.MapperScan; // 注意:這里是導入通用mapper的MapperScan import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan(basePackages = "cn.yujiago.springboot.mapper") // mapper接口的路徑 public class BootApplication { public static void main(String[] args) { SpringApplication.run(BootApplication.class, args); } }
4、model類的配置
@Table(name = "test_table") public class TestTableVO implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator = "JDBC") private Long id; @Transient private String userId; private String name; private Timestamp createTime; private String createUserId; private Timestamp updateTime; private String updateUserId; private Integer isDelete; // 省略get、set... }
說明:
- 表名默認使用類名,駝峰轉下划線(只對大寫字母進行處理),如UserInfo默認對應的表名為user_info
- 表名可以使用@Table(name = “tableName”)進行指定,對不符合第一條默認規則的可以通過這種方式指定表名
- 字段默認和@Column一樣,都會作為表字段,表字段默認為Java對象的Field名字駝峰轉下划線形式
- 可以使用@Column(name = “fieldName”)指定不符合第3條規則的字段名
- 使用@Transient注解可以忽略字段,添加該注解的字段不會作為表字段使用
- 建議一定是有一個@Id注解作為主鍵的字段,可以有多個@Id注解的字段作為聯合主鍵
- 如果是MySQL的自增字段,加上@GeneratedValue(generator = “JDBC”)即可
5、mapper接口的配置
import org.springframework.stereotype.Repository; import tk.mybatis.mapper.common.Mapper; @Repository public interface UserMapper extends Mapper<User> { }
Select 方法:List<T> select(T record); 說明:根據實體中的屬性值進行查詢,查詢條件使用等號 方法:T selectByPrimaryKey(Object key); 說明:根據主鍵字段進行查詢,方法參數必須包含完整的主鍵屬性,查詢條件使用等號 方法:List<T> selectAll(); 說明:查詢全部結果,select(null)方法能達到同樣的效果 方法:T selectOne(T record); 說明:根據實體中的屬性進行查詢,只能有一個返回值,有多個結果是拋出異常,查詢條件使用等號 方法:int selectCount(T record); 說明:根據實體中的屬性查詢總數,查詢條件使用等號 Insert 方法:int insert(T record); 說明:保存一個實體,null的屬性也會保存,不會使用數據庫默認值 方法:int insertSelective(T record); 說明:保存一個實體,null的屬性不會保存,會使用數據庫默認值 Update 方法:int updateByPrimaryKey(T record); 說明:根據主鍵更新實體全部字段,null值會被更新 方法:int updateByPrimaryKeySelective(T record); 說明:根據主鍵更新屬性不為null的值 Delete 方法:int delete(T record); 說明:根據實體屬性作為條件進行刪除,查詢條件使用等號 方法:int deleteByPrimaryKey(Object key); 說明:根據主鍵字段進行刪除,方法參數必須包含完整的主鍵屬性 Example方法 方法:List<T> selectByExample(Object example); 說明:根據Example條件進行查詢 重點:這個查詢支持通過Example類指定查詢列,通過selectProperties方法指定查詢列 方法:int selectCountByExample(Object example); 說明:根據Example條件進行查詢總數 方法:int updateByExample(@Param("record") T record, @Param("example") Object example); 說明:根據Example條件更新實體record包含的全部屬性,null值會被更新 方法:int updateByExampleSelective(@Param("record") T record, @Param("example") Object example); 說明:根據Example條件更新實體record包含的不是null的屬性值 方法:int deleteByExample(Object example); 說明:根據Example條件刪除數據
下面演示大概的寫法:
新增
TestTableVO vo = new TestTableVO(); // 省略為vo設置屬性... int row = testTableDao.insertSelective(vo);
修改
TestTableVO vo = new TestTableVO(); // 省略為vo設置屬性... int row = testTableDao.updateByPrimaryKeySelective(vo);
單個查詢
TestTableVO vo = new TestTableVO(); vo.setId(123L); TestTableVO result = testTableDao.selectOne(vo);
條件查詢
// 創建Example Example example = new Example(TestTableVO.class); // 創建Criteria Example.Criteria criteria = example.createCriteria(); // 添加條件 criteria.andEqualTo("isDelete", 0); criteria.andLike("name", "%abc123%"); List<TestTableVO> list = testTableDao.selectByExample(example);