程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> MyBATIS使用CRUD

MyBATIS使用CRUD

編輯:關於JAVA

MyEclipse不提供自動生成,這裡提供mybatis文件包和開發文檔 http://download.csdn.net/detail/u010026901/7489319

自己建立配置文件,

<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"   />
<dataSource type="POOLED">
<property name="driver" value="oracle.jdbc.driver.OracleDriver"   />
<property name="url" value="jdbc:oracle:thin:@192.168.2.55:ORCL"   />
<property name="username" value="ysk"   />
<property name="password" value="123"   />
</dataSource>
</environment>
</environments>
<mappers>
<!--這裡填寫dao接口映射的daoImpl,mybatis不是映射pojo(vo)類,而是dao類-->
    
<mapper resource="com/kane/dao/NewsDAOImpl.xml"   />
</mappers>
</configuration>

自己配置鏈接的sqlsessionFactory類,相當於hibernate的sessionFactory對應一個數據庫
 

package com.kane.dbc;
    
    
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 MyBATISSqlSessionFactory {
    
    
// 配置文件的所在位置和名稱
private static String CONFIG_FILE_LOCATION = "mybatis-conf.xml";
    
    
// 用來實現連接池的,該類類似Map集合。
private static final ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
// MyBATIS用來讀取配置文件的類
private static InputStream is;
// 用來建立連接的,該類就是連接池,使用單例設計模式
private static SqlSessionFactory sqlsessionFactory;
// 備用的配置文件位置
private static String configFile = CONFIG_FILE_LOCATION;
    
    
// 靜態塊,類加載時最先執行
static {
try {
// 加載配置文件到內存中
is = Resources.getResourceAsStream(configFile);
// 建立連接池以及裡面的連接
sqlsessionFactory = new SqlSessionFactoryBuilder().build(is);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
    
    
private MyBATISSqlSessionFactory() {
}
    
    
/**
* 取得數據庫連接對象
* 
* @return Session
* @throws HibernateException
*/
public static SqlSession getSession() {
// 先從ThreadLocal中取得連接。
SqlSession session = (SqlSession) threadLocal.get();
    
    
// 如果手頭沒有連接,則取得一個新的連接
if (session == null) {
session = sqlsessionFactory.openSession();
// 把取得出的連接記錄到ThreadLocal中,以便下次使用。
threadLocal.set(session);
}
    
    
return session;
}
    
    
/**
* 連接關閉的方法
* 
* @throws HibernateException
*/
public static void closeSession() {
SqlSession session = (SqlSession) threadLocal.get();
// 將ThreadLocal清空,表示當前線程已經沒有連接。
threadLocal.set(null);
// 連接放回到連接池
if (session != null) {
session.close();
}
}
}

通過配置文件實現daoimpl而不是java類

<?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.kane.dao.INewsDAO">
<insert id="doCreate" parameterType="News">
    
<!--jdbcType表示這個內容允許為空,為Oracle指明類型

若表中的列名與vo中列名不同,可以重命名

SELECT
id,title,content,pub_date AS pubDate,type_id AS typeId,photo,tname FROM news n,news_type nt
WHERE id = #{id} AND n.type_id = nt.tid -->
    
INSERT INTO NEWS(news_id,news_title,image_id,news_content,news_time) VALUES
(sys_guid(),#{news_title},#{image_id},#{news_content,jdbcType=VARCHAR},#{news_time,jdbcType=DATE})
</insert>
<delete id="doRemove" parameterType="java.lang.Integer">
DELETE FRON News WHEER news_id=#{id}
</delete>
<update id="doUpdate" parameterType="News">
UPDATE News SET news_title=#{news_title},image_id=#{image_id},news_content=#{news_content},news_time=#{news_time}
WHERE news_id=#{news_id}
</update>
<select id="findAll" resultType="News">
SELECT news_id,news_title,image_id,news_content,news_time FROM News
</select>
<select id="findById" resultType="News">
SELECT news_id,news_title,image_id,news_content,news_time FROM News=#{id}
</select>
<select id="findAllSplit" resultType="News" parameterType="java.util.Map">
SELECT temp.* FROM (SELECT news_id,news_title,image_id,news_content,news_time,ROWNUM rn 
FROM News WHERE ${column} LIKE #{keyword} AND ROWNUM &lt;=#{endNum})
temp WHERE temp.rn>#{startNum}
</select>
<select id="getAllCount" resultType="java.lang.Integer" parameterType="java.util.Map">
SELECT COUNT(*) FROM News WHERE ${column} LIKE #{keyword}
</select>
</mapper>

接著service,在serviceImpl中

package com.kane.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.kane.dao.INewsDAO;
import com.kane.dbc.MyBATISSqlSessionFactory;
import com.kane.service.INewsService;
import com.kane.vo.News;
    
    
public class NewsServiceImpl implements INewsService{
    
    
public List<News> findAll(){
List<News> all=null;
try {
all=MyBATISSqlSessionFactory.getSession().getMapper(INewsDAO.class).findAll();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
MyBATISSqlSessionFactory.closeSession();
}
return all;
}
public void insert(News news) throws Exception {
try {
MyBATISSqlSessionFactory.getSession().getMapper(INewsDAO.class).doCreate(news);
MyBATISSqlSessionFactory.getSession().commit();
} catch (Exception e) {
MyBATISSqlSessionFactory.getSession().rollback();
e.printStackTrace();
}
finally{
MyBATISSqlSessionFactory.closeSession();
}
}
public Map<String, Object> list(int pageNo, int pageSize, String column,String keyword){
Map<String,Object> map=new HashMap<String,Object>();
Map<String,Object> params=new HashMap<String, Object>();
params.put("column",column);
params.put("keyword",keyword);
params.put("endNum",pageSize*pageNo);
params.put("startNum",(pageNo-1)*pageSize);
try {
map.put("allNews", MyBATISSqlSessionFactory.getSession().getMapper(INewsDAO.class)
.findAllSplit(params));
map.put("count", MyBATISSqlSessionFactory.getSession().getMapper(INewsDAO.class)
.getAllCount(params));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
MyBATISSqlSessionFactory.closeSession();
}
return map;
}
public void remove(int id) throws Exception {
// TODO Auto-generated method stub
    
}
public void update(News news) throws Exception {
// TODO Auto-generated method stub
    
}
public News findById(int id){
News news=null;
try {
news=MyBATISSqlSessionFactory.getSession().getMapper(INewsDAO.class).findById(id);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
MyBATISSqlSessionFactory.closeSession();
}
return news;
}
}
    
然後junit測試
    
@Test
public void testList() throws Exception {
System.out.println(ServiceFactory.getNewsServiceInstance().list(1, 5,
"news_title", "12"));
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved