iT邦幫忙

DAY 25
2

java菜鳥的學習筆記系列 第 27

初用MyBatis-失敗

  • 分享至 

  • xImage
  •  

雖然昨天不小心過了十二點才PO文,以致於鐵人賽中斷了,不過我還是想完成這三十天,今天分享初用MyBatis,官網在這:http://blog.mybatis.org/,是一種SQL Mapping的Framework,與Hibernate類似,不過聽說MyBatis比較容易一下所以也就試試看,自行上網找範例、自己try,初用的感想是就像是把JDBC包成一個framework,然後Object與Database mapping的部分與SQL語法部分是寫在XML裡,XML黨名可自己命名,例如自己寫的是Alarm.xml,在定義sqlMapConfig.xml把相關的JDBC連線資料填入,最後以一個DAO類別裡openSession進行相關剛剛在Alarm.xml定義定的查詢,DAO部分的程式碼相當簡潔,大概就是這個MyBatis的優點之一吧!不過我今天自己寫的code有Exception,大家就參考參考,架構是對的

參考網址:http://loianegroner.com/2011/02/getting-started-with-ibatis-mybatis-xml-configuration/
Alarm.java

package alarm;

import javax.xml.bind.annotation.XmlRootElement;


@XmlRootElement
public class Alarm {
	private int id;
	private String refid;
	private String aid;
	private String des;
	private String state;
	private String sys;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	
	public String getRefid() {
		return refid;
	}
	public void setRefid(String refid) {
		this.refid = refid;
	}
	public String getAlarmid() {
		return aid;
	}
	public void setAlarmid(String alarmid) {
		this.aid = alarmid;
	}
	public String getDes() {
		return des;
	}
	public void setDes(String des) {
		this.des = des;
	}
	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}
	public String getSys() {
		return sys;
	}
	public void setSys(String sys) {
		this.sys = sys;
	}
}

Alarm.xml

<?xml version="1.0" encoding="UTF-8"?>


 
<mapper namespace="Alarm">
 
    <resultMap id="result" type="Alarm">
       <result property="id" column="id"/>
        <result property="aid" column="alarmid"/>
        <result property="refid" column="refid"/>
        <result property="des" column="description"/>
        <result property="state" column="state"/>
        <result property="sys" column="system"/>
    </resultMap>
 
    <select id="getAll" resultMap="result">
        SELECT * FROM Alarm
    </select>
 
    <select id="getBySys" parameterType="String" resultMap="result">
        SELECT * FROM Alarm WHERE system = #{sys}
    </select>
 
    
 	 <insert id="insert" parameterType="Alarm">
    INSERT INTO Alarm (id, refid, alarmid, description, state, system) //編譯的時候說我SQL語法有錯@@
        VALUES (#{id}, #{refid}, #{aid},{des}, {state}, {sys});
      <selectKey keyProperty="id" resultType="int" order="AFTER">
        select last_insert_id() as id
      </selectKey>
    </insert>
</mapper>

MyBatisConnFactory

package mybatis;

import java.io.Reader;

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

public class MyBatisConnFactory {
	private static SqlSessionFactory ssessfactory;
	
	static{
		try{
			String resource ="SqlMapConfig.xml";
			Reader reader= Resources.getResourceAsReader(resource);
			if(ssessfactory ==null){
				ssessfactory= new SqlSessionFactoryBuilder().build(reader);
			}
		
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	public static SqlSessionFactory getSsessfactory() {
		return ssessfactory;
	}

AlarmDAO

package dao.Alarm;

import java.util.Iterator;
import java.util.List;

import mybatis.MyBatisConnFactory;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import read.GetDataFromFile;

import alarm.Alarm;

public class AlarmDAO {
			private SqlSessionFactory ssessfactory;
			public AlarmDAO(){
				ssessfactory = MyBatisConnFactory.getSsessfactory();
			}
				public List<Alarm> listAll(){
					SqlSession session = ssessfactory.openSession();
					try{
						List<Alarm> alist= session.selectList("Alarm.getAll");
						return alist;
					}finally{
						session.close();
					}
				}
				public void insert(){
					SqlSession session = ssessfactory.openSession();
					 
			        try {
			            GetDataFromFile gf= new GetDataFromFile();
			            List<Alarm> alist =gf.readFromExcel();
			            Iterator<Alarm> it=alist.iterator();
						while(it.hasNext()){
							session.insert("Alarm.insert", it.next());
							session.commit();
						}
			           
			        } finally {
			            session.close();
			        }
				}
			}

Exception:

用MyBatis新增資料失敗,但是自己土法煉鋼卻成功@@

public void writeInDB(List<Alarm> list){
				String sql="INSERT into Alarm (alarmid, refid, description, state, system)"
			                       +"values (?,?,?,?,?)";
				try {
					DBConnection db=new DBConnection();
					Connection conn=db.getConnection();
					PreparedStatement prestmt=conn.prepareStatement(sql);
					Iterator<Alarm> it=list.iterator();
					while(it.hasNext()){
						prestmt.setString(1, it.next().getAlarmid());
						prestmt.setString(2, it.next().getRefid());
						prestmt.setString(3, it.next().getDes());
						prestmt.setString(4, it.next().getState());
						prestmt.setString(5, it.next().getSys());
						prestmt.addBatch();
					}
						int [] result = prestmt.executeBatch();
						prestmt.execute();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}

結果:


上一篇
綜合練習-從Excel讀入資料並用Collection處理後再輸出
下一篇
MyBatis使用-插入資料成功!(雖然這是很基本的功能....)
系列文
java菜鳥的學習筆記28
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 則留言

0
fillano
iT邦超人 1 級 ‧ 2012-11-05 11:35:46

myBatis是包裝了iBatis嗎?

是的!!

0
ted99tw
iT邦高手 1 級 ‧ 2012-11-05 17:35:21

joombuopre提到:
雖然昨天不小心過了十二點才PO文,以致於鐵人賽中斷了

我咧,就在最後一兩天......驚

是說技術鐵文又少了一個強勁對手,接下來要買阿德的美濃瓜又更進一步了啦~~~偷笑

我要留言

立即登入留言