MybatisPlus--基礎查詢與分頁
阿新 • • 發佈:2019-01-02
<!-- Mybatis外掛 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.1.8</version>
</dependency>
Spring配置檔案:
資料來源與Mybatis-Plus中與SqlSessionFactory類似的Session工廠。
<!-- - - - - - - - Apache 連線池 - - - - - - - -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="username" value="root" />
<property name ="password" value="123123" />
<property name="url"
value="jdbc:mysql://127.0.0.1:3306/mybatis-plus?characterEncoding=utf8&useSSL=true" />
</bean>
<bean id="sqlSessionFactory"
class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自動掃描Mapping.xml檔案 -->
<property name="mapperLocations"
value="classpath:com/test/mybatisplus/dao/mapper/*.xml" />
<property name="configLocation" value="classpath:sqlMapConfig.xml" />
<property name="typeAliasesPackage" value="com.test.mybatisplus.pojo" />
<property name="plugins">
<array>
<!-- 分頁外掛配置 -->
<bean id="paginationInterceptor"
class="com.baomidou.mybatisplus.plugins.PaginationInterceptor">
<property name="dialectType" value="mysql" />
</bean>
<bean id="performanceInterceptor"
class="com.baomidou.mybatisplus.plugins.PerformanceInterceptor" >
<!-- 超過自動停止執行,有助於發現問題。 -->
<property name="maxTime" value="100" />
<!--SQL是否格式化 預設false-->
<property name="format" value="true" />
</bean>
</array>
</property>
<!-- 全域性配置注入 -->
<property name="globalConfig" ref="globalConfig" />
</bean>
<bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
<property name="idType" value="2" />
<property name="dbColumnUnderline" value="true" />
</bean>
<!-- MyBatis 掃描*Dao.java介面 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.test.mybatisplus.dao" />
</bean>
Mybatis相關配置:
<configuration>
<!-- - - - - - - 懶載入和快取 - - - - - - - - - - -->
<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
</configuration>
整合完畢。
可在官網找到根據資料庫選擇表後自動生成一系列的程式碼。如下我整理的程式碼。
public static void main(String[] args) {
// TODO Auto-generated method stub
generateCode(new String[] { "user" });
}
/**
* Dao、Mapper、Service和、Controller生成程式碼
*
* @param tabelNames
* 表名
*/
public static void generateCode(String[] tabelNames) {
AutoGenerator mpg = new AutoGenerator();
// 全域性配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir("D://");// 建立的檔案輸出目錄
gc.setFileOverride(true);// 覆蓋已有檔案
gc.setActiveRecord(true);// 不需要ActiveRecord特性的請改為false
gc.setEnableCache(false);// XML 二級快取
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(true);// XML columList
gc.setAuthor("Tang");// 類作者
// 檔名
gc.setMapperName("%sDao");
gc.setXmlName("%sMapper");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImpl");
gc.setControllerName("%sController");
mpg.setGlobalConfig(gc);
// 資料來源
DataSourceConfig dataSourceConfig = getDataSourceConfig();
mpg.setDataSource(dataSourceConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
strategy.setInclude(tabelNames); // 需要生成相關程式碼的表名
strategy.setSuperMapperClass("com.baomidou.mybatisplus.mapper.BaseMapper");// 自定義 dao 父類
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent(null);
pc.setEntity("com.test.mybatisplus.pojo");
pc.setMapper("com.test.mybatisplus.dao");// Dao介面包名
pc.setXml("com.test.mybatisplus.dao.mapper");// XML包名
pc.setService("com.test.mybatisplus.service");
pc.setServiceImpl("com.test.mybatisplus.service.impl");
pc.setController("com.test.mybatisplus.controller");
mpg.setPackageInfo(pc);
// 執行生成
mpg.execute();
System.out.println("run over");
}
/**
* 資料來源設定
* @return
*/
private static DataSourceConfig getDataSourceConfig() {
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setTypeConvert(new MySqlTypeConvert() {
// 自定義資料庫表字段型別轉換【可選】
public DbColumnType processTypeConvert(String fieldType) {
System.out.println("轉換型別:" + fieldType);
// 注意!!processTypeConvert 存在預設型別轉換,如果不是你要的效果請自定義返回、非如下直接返回。
return super.processTypeConvert(fieldType);
}
});
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123123");
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/mybatis-plus?characterEncoding=utf8");
return dsc;
}
專案結構:
2 基礎增刪改查
Dao層:
public interface UserDao extends BaseMapper<User> {
/**
* 測試自己手寫的SQL及介面
* @param id
* @return
*/
public User selectByPrimaryId(Integer id);
}
對應的Mapper:
<mapper namespace="com.test.mybatisplus.dao.UserDao">
<!-- 通用查詢對映結果 -->
<resultMap id="BaseResultMap" type="com.test.mybatisplus.pojo.User">
<id column="id" property="id" />
<result column="name" property="name" />
<result column="password" property="password" />
</resultMap>
<!-- 通用查詢結果列 -->
<sql id="Base_Column_List">
id, name, password
</sql>
<!-- 測試手寫的SQL -->
<select id="selectByPrimaryId" parameterType="java.lang.Integer"
resultType="com.test.mybatisplus.pojo.User">
SELECT
<include refid="Base_Column_List" />
FROM user
WHERE id=#{id}
</select>
</mapper>
Pojo類:
public class User extends Model<User> {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String name;
private String password;
//省略get/set
測試程式碼:
public static void testCrud() {
// 自己手寫的方式
//System.out.println(userDao.selectByPrimaryId(1));
// 自動生成的程式碼
// 增
/*User user01 = new User();
user01.setName("測試新增");
userDao.insert(user01);*/
//刪
/*Integer influenceRows = userDao.deleteById(2);
System.out.println("影響行數:"+influenceRows);*/
//修改
User user02=new User();
user02.setId(3);
user02.setName("update測試");
System.out.println("update影響行數"+userDao.updateById(user02));
// 查
User user03 = userDao.selectById(3);
System.out.println(user03);
//分頁查詢
Wrapper<User> entity = new EntityWrapper<User>();
entity.like("name", "%測試%");
entity.between("id", 1, 3);
List<User> lstUser = userDao.selectPage(new Page<User>(1,10),entity);
for(User user:lstUser) {
System.out.println(user);
}
}
3 分頁
確保配置檔案中整合了分頁外掛
在xml中只需要需要寫如下的程式碼即可實現分頁:
<select id="selectUserList" parameterType="map" resultType="com.test.mybatisplus.pojo.User">
SELECT
<include refid="Base_Column_List" />
FROM user
WHERE name LIKE CONCAT("%",#{name},"%")
</select>
測試:
/**
* 分頁外掛
*/
public static void testPageListUser() {
Page<User> page = new Page<User>(1,10);
Map<String, Object> condition=new HashMap<String, Object>();
condition.put("name", "測試");
//String name="測試";
List<User> lstUser = userDao.selectUserList(page,condition);
for(User user:lstUser) {
System.out.println(user);
}
}