上一章Spring集成MyBatis进行项目开发(一)已经介绍了spring3和mybatis整合的配置,接下来是一个项目里面的部分代码:
Application.java是下面会用到的一个实体bean:
public class Application {
public static final int APP_DISABLE = 0;
public static final int APP_ENABLE = 1;
private Integer id;
private String appAccount;//每个app对应一个账户标识;对应生成的数据表
private String appName;
private String appICON;
private String appDesc;
private String appURL;
private Date createTime;
private int isDisable;//'是否前台显示:0显示,1不显示'
}
getter 和setter略。
首先我们要编写一个与mapper.xml文件映射的接口文件,mybatis会将这个接口文件和对应的mapper文件中的sql语句关联,自动实现这个接口文件。在之后的开发中我们直接调用这个接口文件就可以了,因为内存中已经有接口相对应的实例了。
ApplicationsMapper.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.pinche.statistic.mapper.ApplicationsMapper"> <insert id="add" parameterType="Application" useGeneratedKeys="true" keyProperty="id"> INSERT INTO applications (appName,appAccount,appICON,appDesc,appURL,createTime) VALUES (#{appName},#{appAccount},#{appICON},#{appDesc},#{appURL},#{createTime}) </insert> <delete id="delete" parameterType="String"> DELETE FROM applications WHERE appAccount = #{appAccount} </delete> <update id="update" parameterType="Application"> UPDATE applications <set> <if test=" appName != '' and appName != null "> appName = #{appName}, </if> <if test=" appICON != '' and appICON != null "> appICON = #{appICON}, </if> <if test=" appDesc != '' and appDesc != null "> appDesc = #{appDesc}, </if> <if test=" appURL != '' and appURL != null "> appURL = #{appURL}, </if> <if test=" isDisable != -1 "> isDisable = #{isDisable} </if> </set> WHERE appAccount = #{appAccount} </update> <select id="findByAppAccount" resultType="Application" parameterType="String"> select * from applications where appAccount = #{appAccount} </select> <select id="findAll" resultType="Application"> select * from applications </select> </mapper>
对ApplicationsMapper.xml文件的配置必须要注意的是它的命名空间是必须的,而且是对应接口文件的全名!并且每个sql语句的id属性和接口文件中的方法名一致!!
下面是ApplicationsMapper.java文件,也就是对应的接口文件:
package com.pinche.statistic.mapper;
import java.util.List;
import com.pinche.statistic.domain.Application;
public interface ApplicationsMapper {
void add(Application app);
void delete(String appAccount);
void update(Application app);
Application findByAppAccount(String appAccount);
List<Application> findAll();
}
通过以上的的配置,大家可以在test中测试一下自己的代码了:
@Test
public void testCreateTable() {
ApplicationContext aContext = new FileSystemXmlApplicationContext("src/main/webapp/WEB-INF/applicationContext.xml");
ApplicationsMapper mapper = (ApplicationsMapper) aContext.getBean(ApplicationsMapper.class);
Application app = new Application();
app.setAppAccount("androidApp");
mapper.add(app);
}
以上测试了add方法,其他的测试方法大家可以照着写一写。如果插入成功恭喜,你的环境已经搭好了。
接下来是将继续这个样例系统的Dao层,service层和controller层。
这个dao层吧,项目中就是这么用的,不过现在通过大家的指正,mybatis提供了@param来解决多参数问题,ok,这么看来这个Dao层的确不需要了。
AppDao.java:
package com.pinche.statistic.dao;
import java.util.List;
import com.pinche.statistic.domain.Application;
public interface AppDao {
boolean add(Application app);
boolean delete(String appAccount);
boolean update(Application app);
Application findByAppAccount(String appAccount);
List<Application> findAll();
}
对应的实现类AppDaoImpl.java
package com.pinche.statistic.dao.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import com.pinche.statistic.dao.AppDao;
import com.pinche.statistic.domain.Application;
import com.pinche.statistic.mapper.ApplicationsMapper;
@Repository
public class AppDaoImpl implements AppDao {
@Autowired
private ApplicationsMapper mapper;
@Override
public boolean add(Application app) {
try {
mapper.add(app);
return true;
} catch (DataAccessException e) {
e.printStackTrace();
}
return false;
}
@Override
public boolean delete(String appAccount) {
try {
mapper.delete(appAccount);
return true;
} catch (DataAccessException e) {
e.printStackTrace();
}
return false;
}
@Override
public boolean update(Application app) {
try {
mapper.update(app);
return true;
} catch (DataAccessException e) {
e.printStackTrace();
}
return false;
}
@Override
public Application findByAppAccount(String appAccount) {
try {
Application findByAppAccount = mapper.findByAppAccount(appAccount);
return findByAppAccount;
} catch (DataAccessException e) {
e.printStackTrace();
}
return null;
}
@Override
public List<Application> findAll() {
try {
return mapper.findAll();
} catch (DataAccessException e) {
e.printStackTrace();
}
return null;
}
}
自行设计的DAO层对象容器(在DAO对象很多时,如果在service层要调用对应的DAO还得手动注入,通过引用这个DAO层对象容器,可以实现在需要使用DAO时迅速找需要的DAO,省去了繁杂的手动注入,而且spring默认的bean都是单例的,无论在何处注入一个实体bean其实都是同一个。这样做更方便):
package com.pinche.statistic.dao;
import java.lang.reflect.Field;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class BaseDAL {
private static final Logger logger = LoggerFactory.getLogger(BaseDAL.class);
@Autowired
private AppDao _appDao;
public static AppDao appDao;
@Autowired
private MetaDataDao _metaDataDao;
public static MetaDataDao metaDataDao;
@Autowired
private DDLManager _DDLManager;
public static DDLManager DDLManager;
@Autowired
private AnalyzeDao _analyzeDao;
public static AnalyzeDao analyzeDao;
@Autowired
private DialstatisticsDao _dialstatisticsDao;
public static DialstatisticsDao dialstatisticsDao;
@PostConstruct
public void init() {
long start = System.currentTimeMillis();
logger.debug("start init BaseDAL ...");
try {
Field[] fields = this.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
String fieldname = fields[i].getName();
if (fieldname.startsWith("_")) {
String sfieldname = fieldname.substring(1);
Field sfield = this.getClass().getDeclaredField(sfieldname);
sfield.setAccessible(true);
sfield.set(this, fields[i].get(this));
}
}
logger.debug("init BaseDAL OVER, consume = {}ms",
System.currentTimeMillis() - start);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
如果使用了以上的层管理容器,如果要在容器中添加一个DAO(例如:DemoDao),只需在这个容器中添加一个这样的声明:
@Autowired
private DemoDao _demoDao;
public static DemoDao demoDao;
好了下面是Service层定义的接口:
AppService.java
package com.pinche.statistic.service;
import java.util.List;
import com.pinche.statistic.domain.Application;
/**
* @author JACKWANG
* @since Dec 23, 2013
*/
public interface AppService {
Application find(String appAccount);
boolean update(Application app);
boolean setDisable(String appAccount);
boolean setEnable(String appAccount);
List<Application> findAll();
}
AppServiceImpl.java : AppService的实现类:
package com.pinche.statistic.service.impl;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.pinche.statistic.dao.BaseDAL;
import com.pinche.statistic.domain.Application;
import com.pinche.statistic.service.AppService;
import com.pinche.statistic.utils.SystemUtils;
/**
* @author JACKWANG
* @since Dec 23, 2013
*/
@Service
public class AppServiceImpl implements AppService {
private static final Logger logger = LoggerFactory
.getLogger(AppServiceImpl.class);
@Override
public Application find(String appAccount) {
return BaseDAL.appDao.findByAppAccount(appAccount);
}
@Override
public boolean update(Application app) {
String appAccount = app.getAppAccount();
if (appAccount == null && "".equals(appAccount)) {
return true;
}
return BaseDAL.appDao.update(app);
}
@Override
public boolean setDisable(String appAccount) {
Application app = new Application();
app.setAppAccount(appAccount);
app.setIsDisable(Application.APP_DISABLE);
return BaseDAL.appDao.update(app);
}
@Override
public boolean setEnable(String appAccount) {
Application app = new Application();
app.setAppAccount(appAccount);
app.setIsDisable(Application.APP_ENABLE);
return BaseDAL.appDao.update(app);
}
@Override
public List<Application> findAll() {
return BaseDAL.appDao.findAll();
}
}
哈哈,使用层对象管理容器是不是很方便。通过一个引用就能获得所有的DAO支持。所以我在service层也构建了一个service层对象管理容器BaseBLL:
BaseBLL.java:
package com.pinche.statistic.service;
import java.lang.reflect.Field;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author JACKWANG
* @since Dec 23, 2013
*/
@Service
public class BaseBLL {
private static final Logger logger = LoggerFactory.getLogger(BaseBLL.class);
@Autowired
private AnalyzeService _analyzeService;
public static AnalyzeService analyzeService;
@Autowired
private AppService _appService;
public static AppService appService;
@Autowired
private MetaDataService _metaDataService;
public static MetaDataService metaDataService;
@PostConstruct
public void init() {
long start = System.currentTimeMillis();
logger.debug("start init BaseBLL ...");
try {
Field[] fields = this.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
String fieldname = fields[i].getName();
if (fieldname.startsWith("_")) {
String sfieldname = fieldname.substring(1);
Field sfield = this.getClass().getDeclaredField(sfieldname);
sfield.setAccessible(true);
sfield.set(this, fields[i].get(this));
}
}
logger.debug("init BaseBLL OVER, consume = {}ms",
System.currentTimeMillis() - start);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
好了下面应该是controller层的编写了,但是由于笔者以上的代码只是摘录了系统中的部分,而在controller中涉及到其他的内容,如果直接摘录可能和以上的代码衔接不上。所以这里就不进行了controller层的具体介绍了。本系统controller层使用的是SpringMVC,开发效率一级赞。