您的位置:首页 > 其它

mybatis接口式的模糊查询、分页、增删改、事务处理

2014-08-09 06:57 423 查看
这次我们把上次的改为接口式的

目录结构如下



这次添加了一个InfoLogMapper这个接口,InfoLog.xml中的命名空间必须是指向InfoLogMaper

的完整路径



BaseDao.java

package com.iweye.ssm.dao;

import org.apache.ibatis.session.SqlSession;

import com.iweye.ssm.util.DBUtil;

public class BaseDao {
public SqlSession getSession() {
return DBUtil.getSession();
}
}
InfoLogDao

package com.iweye.ssm.dao;

import java.util.List;
import java.util.Map;

import com.iweye.ssm.pojo.InfoLog;

public class InfoLogDao extends BaseDao{
/**
* 查询所有
* @return
*/
public List<InfoLog> getAll() {
try {
List<InfoLog> list = getSession().selectList("com.iweye.ssm.dao.InfoLogMapper.selectAllInfoLogs");
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
}
}
/**
* 查询一个数据
* @param infoLog
* @return
*/
public InfoLog selectInfoLog(InfoLog infoLog) {
try {
InfoLog list = getSession().selectOne("com.iweye.ssm.dao.InfoLogMapper.selectInfoLog", infoLog);
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
}
}
public Long selectAllInfoLogsCount(){
try {
return getSession().selectOne("com.iweye.ssm.dao.InfoLogMapper.selectAllInfoLogsCount");
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
}
}
public List<InfoLog> selectAllInfoLogForPage(Map<String, String> map) {
try {
List<InfoLog> list = getSession().selectList("com.iweye.ssm.dao.InfoLogMapper.selectAllInfoLogForPage",	map);
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
}
}
public boolean addInfoLog(InfoLog infoLog) {
try {
getSession().insert("com.iweye.ssm.dao.InfoLogMapper.addInfoLog", infoLog);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
}
}
public boolean updateInfoLog(InfoLog infolog) {
try {
getSession().update("com.iweye.ssm.dao.InfoLogMapper.updateInfoLog",infolog);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
}
}
public boolean deleteInfoLog(InfoLog infolog) {
try {
getSession().delete("com.iweye.ssm.dao.InfoLogMapper.deleteInfoLog",infolog);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
}
}
}
InfoLog.xml

<pre name="code" class="html"><?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.iweye.ssm.dao.InfoLogMapper">
<select id="selectAllInfoLogs" resultType="InfoLog">
select * from info_log
</select>
<select id="selectAllInfoLogsCount" resultType="java.lang.Long"  >
select count(*) from info_log
</select>
<select id="selectInfoLog"  parameterType="InfoLog"   resultType="InfoLog">
SELECT * from info_log
WHERE operator = #{operator}
and createdate=#{createdate} and createtime=#{createtime}
</select>

<insert id="addInfoLog" parameterType="InfoLog"  >
insert into info_log(operator,createdate,createtime,mac,annex)
values(#{operator},#{createdate},#{createtime},#{mac},#{annex})
</insert>
<update id="updateInfoLog" parameterType="InfoLog"  >
update  info_log set createdate=#{createdate},createtime=#{createtime},mac=#{mac},annex=#{annex}
where operator=#{operator} and createdate=#{createdate} and createtime=#{createtime}
</update>
<select id="selectAllInfoLogForPage"  parameterType="java.util.Map"   resultType="InfoLog">
SELECT * FROM ( SELECT A.*, ROWNUM RN  FROM (
select * from info_Log  where
<![CDATA[createdate>=#{startDate} and createdate<=#{endDate}]]>
and operator	like  '%'||#{operator}||'%'
) A WHERE <![CDATA[ ROWNUM <= #{end} ) WHERE RN >= #{start} ]]>
</select>
<delete id="deleteInfoLog" parameterType="InfoLog"  >
delete from   info_log
where operator=#{operator} and createdate=#{createdate} and createtime=#{createtime}
</delete>
</mapper>



InfoLog

package com.iweye.ssm.pojo;

/**
* 员工日志表-
* @auto  <a href="mailto:1808857902@qq.com">wei_xing</a>
* @time 2014-5-26 下午03:23:48
* @version 2014
*/

public class InfoLog implements java.io.Serializable {

private static final long serialVersionUID = 1L;
private String operator;
private Integer createdate;
private Integer createtime;
private String mac;
private String annex;

// Constructors

/** default constructor */
public InfoLog() {
}

/** minimal constructor */
public InfoLog(String operator) {
this.operator = operator;
}

/** full constructor */
public InfoLog(String operator, Integer createdate, Integer createtime, String mac, String annex) {
this.operator = operator;
this.createdate = createdate;
this.createtime = createtime;
this.mac = mac;
this.annex = annex;
}
public InfoLog(String operator,  String mac, String annex) {
this.operator = operator;
this.mac = mac;
this.annex = annex;
}
// Property accessors

public String getOperator() {
return this.operator;
}

public void setOperator(String operator) {
this.operator = operator;
}

public Integer getCreatedate() {
return this.createdate;
}

public void setCreatedate(Integer createdate) {
this.createdate = createdate;
}

public Integer getCreatetime() {
return this.createtime;
}

public void setCreatetime(Integer createtime) {
this.createtime = createtime;
}

public String getMac() {
return this.mac;
}

public void setMac(String mac) {
this.mac = mac;
}

public String getAnnex() {
return this.annex;
}

public void setAnnex(String annex) {
this.annex = annex;
}

public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof InfoLog))
return false;
InfoLog castOther = (InfoLog) other;

return ((this.getOperator() == castOther.getOperator()) || (this
.getOperator() != null
&& castOther.getOperator() != null && this.getOperator()
.equals(castOther.getOperator())))
&& ((this.getCreatedate() == castOther.getCreatedate()) || (this
.getCreatedate() != null
&& castOther.getCreatedate() != null && this
.getCreatedate().equals(castOther.getCreatedate())))
&& ((this.getCreatetime() == castOther.getCreatetime()) || (this
.getCreatetime() != null
&& castOther.getCreatetime() != null && this
.getCreatetime().equals(castOther.getCreatetime())))
&& ((this.getMac() == castOther.getMac()) || (this.getMac() != null
&& castOther.getMac() != null && this.getMac().equals(
castOther.getMac())))
&& ((this.getAnnex() == castOther.getAnnex()) || (this
.getAnnex() != null
&& castOther.getAnnex() != null && this.getAnnex()
.equals(castOther.getAnnex())));
}

public int hashCode() {
int result = 17;

result = 37 * result
+ (getOperator() == null ? 0 : this.getOperator().hashCode());
result = 37
* result
+ (getCreatedate() == null ? 0 : this.getCreatedate()
.hashCode());
result = 37
* result
+ (getCreatetime() == null ? 0 : this.getCreatetime()
.hashCode());
result = 37 * result
+ (getMac() == null ? 0 : this.getMac().hashCode());
result = 37 * result
+ (getAnnex() == null ? 0 : this.getAnnex().hashCode());
return result;
}

@Override
public String toString() {
return "InfoLog [operator=" + operator + ", createdate=" + createdate
+ ", createtime=" + createtime + ", mac=" + mac + ", annex="
+ annex + "]";
}

}
DBUtil

package com.iweye.ssm.util;

import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class DBUtil {

public DBUtil() {
}
// 配置文件的所在位置和名称
private static String resource = "mybatis-config.xml";
// 存放连接池
private static final ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
// 用来建立连接的,该类就是连接池,使用单例设计模式
private static SqlSessionFactory sqlSessionFactory;
// 由于SessionFactory是重量级的,所以只实例化一次
static {
try {
// 加载配置文件到内存中
InputStream inputStream = Resources.getResourceAsStream(resource);
// 建立连接池以及里面的连接
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 单例模式 取得数据库连接对象
* @return
*/
public static SqlSession getSession() {
// 如果没有连接,则取得一个新的连接
SqlSession session = threadLocal.get();
if (session == null) {
session = sqlSessionFactory.openSession();
// 把取得出的连接记录到ThreadLocal中,以便下次使用。
threadLocal.set(session);
}
return session;
}

/**
* 关闭连接
*/
public static void closeSession() {
SqlSession session = (SqlSession) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}

public static void main(String[] args) {
System.err.println(getSession());
}
}
config.properties

driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:orcl
username=scott
password=tiger
mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 引用资源文件 -->
<properties resource="config.properties"  />
<!-- 类型别名是为 Java 类型命名一个短的名字 -->
<typeAliases>
<typeAlias alias="InfoLog" type="com.iweye.ssm.pojo.InfoLog"/>
</typeAliases>

<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
</environments>

<mappers>
<mapper resource="com/iweye/ssm/dao/InfoLog.xml" />
</mappers>
</configuration>
下面是测试类,用的是junit来单元测试的

TestDemo

package com.iweye.ssm.test;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.apache.ibatis.transaction.Transaction;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.junit.Test;

import com.iweye.ssm.dao.InfoLogDao;
import com.iweye.ssm.pojo.InfoLog;
import com.iweye.ssm.util.DBUtil;

/**
* 从 XML 中构建 SqlSessionFactory
*
* @auto <a href="mailto:1808857902@qq.com">wei_xing</a>
* @time 2014年8月7日下午4:21:55
* @version 2014
*/
public class TestDemo {
@Test
public void addInfoLog() throws SQLException{
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Transaction  newTransaction=transactionFactory.newTransaction(DBUtil.getSession().getConnection());
try {
InfoLogDao ild = new InfoLogDao();
int cout = 808;
for (int i = 0; i < 40; i++) {
InfoLog infoLog = new InfoLog();
infoLog.setOperator("" + (cout + i));
infoLog.setCreatedate(20140804);
infoLog.setCreatetime(183521);
infoLog.setMac("999:3:" + i + "");
infoLog.setAnnex("时间" + i + "");
ild.addInfoLog(infoLog);
}
//#############打印总数###################//
System.err.println("总数:"+ild.selectAllInfoLogsCount());
//#############打印###################//
for(InfoLog log : ild.getAll()){
System.err.println(log.toString());
}
} catch (Exception e) {
newTransaction.rollback();
}finally{
newTransaction.commit();
newTransaction.close();
}
}
@Test
public void selectAllInfoLogs(){
InfoLogDao ild=new InfoLogDao();
for(InfoLog log : ild.getAll()){
System.err.println(log.toString());
}
}
@Test
public void selectInfoLog(){
InfoLog infoLog = new InfoLog();
infoLog.setOperator("811");
infoLog.setCreatedate(20140804);
infoLog.setCreatetime(183521);
System.err.println(new InfoLogDao().selectInfoLog(infoLog));
}
@Test//分页
public void selectAllInfoLogForPage(){
Map<String,String> map = new HashMap<String,String>();
map.put("startDate", "20140702");
map.put("endDate", "20140809");
map.put("operator", "5");
map.put("start", "1");
map.put("end", "20");
for(InfoLog log : new InfoLogDao().selectAllInfoLogForPage(map)){
System.err.println(log.toString());
}
}
@Test //修改
public void update() throws SQLException{
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Transaction  newTransaction=transactionFactory.newTransaction(DBUtil.getSession().getConnection());
try {
InfoLog infolog = new InfoLog();
infolog.setAnnex("时间71111");
infolog.setOperator("815");
infolog.setCreatedate(20140804);
infolog.setCreatetime(183521);
infolog.setMac("999:3:7111");
System.err.println(new InfoLogDao().updateInfoLog(infolog));

System.err.println(new InfoLogDao().selectInfoLog(infolog));
} catch (Exception e) {
newTransaction.rollback();
}finally{
newTransaction.commit();
newTransaction.close();
}
}

@Test //删除
public void delete() throws SQLException{
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Transaction  newTransaction=transactionFactory.newTransaction(DBUtil.getSession().getConnection());
try {
InfoLog infolog = new InfoLog();
infolog.setAnnex("时间71111");
infolog.setOperator("815");
infolog.setCreatedate(20140804);
infolog.setCreatetime(183521);
infolog.setMac("999:3:7111");
System.err.println(new InfoLogDao().deleteInfoLog(infolog));

System.err.println(new InfoLogDao().selectInfoLog(infolog));
} catch (Exception e) {
newTransaction.rollback();
}finally{
newTransaction.commit();
newTransaction.close();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: