Mybatils框架 – JAVA編程語言程序開發技術文章

Mybatils框架
1.什麼是Mybatis
Mybatis是對JDBC的封裝,它隱藏瞭具體的JDBC的API,它把SQL語句放到瞭配置文件中,它能自動把不同的輸入數據映射到SQL語句的動態參數上,它能自動把SQL語句的執行結果映射為JAVA對象…… MyBatis是一個持久化層的框架!
Mybatis是一個ORM框架
可以說Mybatis是一個半自動的ORM框架,Hibernate是全自動的
2.
 
配置文件(SqlMapConfig.xml)
基本作用就是配置JDBC連接的有關信息,比如URL、用戶名、密碼等等
如:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
       <typeAlias type="cn.com.leadfar.cms.backend.model.Admin" alias="Admin"/>
    </typeAliases>
    <environments default="development">
       <environment id="development">
           <transactionManager type="JDBC" />
           <dataSource type="POOLED">
              <property name="driver" value="com.mysql.jdbc.Driver" />
              <property name="url" value="jdbc:mysql://localhost/cms" />
              <property name="username" value="root" />
              <property name="password" value="mysql" />
           </dataSource>
       </environment>
    </environments>
    <mappers>
       <mapper resource="cn/com/leadfar/cms/backend/dao/impl/AdminMapper.xml" />
    </mappers>
</configuration>
 
映射文件
 
基本作用就是編寫SQL語句,同時給每個SQL語句定義一個唯一標識(ID),在程序中通過此ID來調用這條SQL語句。
 
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.leadfar.cms.backend.model.Admin">
    <insert id="add" parameterType="Admin">
       insert into t_admin (username,password) values (#{username},#{password})
    </insert>
</mapper>
 
程序代碼
 
       //創建SqlSession的工廠!
       SqlSessionFactory factory = null;
       try {
           //通過配置文件,創建工廠對象
           Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
           factory = new SqlSessionFactoryBuilder().build(reader);
       } catch (IOException e1) {
           e1.printStackTrace();
       }
     
       //打開一個session
       SqlSession session = factory.openSession();
     
       try {
           //插入
           session.insert("cn.com.leadfar.cms.backend.model.Admin.add", admin);
         
           //提交事務
           session.commit();
         
       } catch (Exception e) {
           e.printStackTrace();
           session.rollback();
       } finally{
           //關閉session
           session.close();
       }
 
 3.兩種xml文件的配置
(1)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!– 整個唯一標識sql的id為namespace+id  org.leadfar.mybatis.Person.insert–>
<mapper namespace="org.leadfar.Student">
<insert id="insert"  parameterType="Student">
insert into t_user (id,name,age,birthday,money)values(seq_user_id.nextval,#{name},#{age} ,#{birthday} ,#{money})
</insert>
<update id="update"  parameterType="Student">
update t_user  set name=#{name},age=#{age},birthday=#{birthday},money=#{money} where id=#{id}
</update>
<delete id="delete"  parameterType="Student">
delete t_user  where id=#{id}
</delete>
<select id="selectone"  parameterType="int" resultType="Student">
select *  from t_user  where id=#{id}
</select>
</mapper>
(2)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<!– 配置管理器 –>
<configuration>
    <!– 別名 –>
    <typeAliases>
       <typeAlias type="org.leadfar.Student" alias="Student"/>
    </typeAliases>
    <!– 配置數據庫連接信息 –>
    <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:@localhost:1521:leadfar" />
              <property name="username" value="bbs" />
              <property name="password" value="bbs" />
           </dataSource>
       </environment>
    </environments>
    <!– 映射文件定位 –>
    <mappers>
       <mapper resource="org/leadfar/SqlMapStudent.xml" />
    </mappers>
</configuration>
(3)dao層
package org.leadfar;
import java.io.IOException;
import java.io.Reader;
import java.util.Date;
import junit.framework.TestCase;
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 StudentDaoTest extends TestCase {
private SqlSessionFactory factory ;
@Override
protected void setUp() throws Exception {
Reader reader = null;
try {
reader = Resources.getResourceAsReader("Mybatils.xml");
factory =new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("讀取Mybatils.xml文件失敗");
}
}
public void testSave() {
SqlSessionFactory factory = null;
Reader reader = null;
try {
reader = Resources.getResourceAsReader("Mybatils.xml");
factory =new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("讀取Mybatils.xml文件失敗");
}
SqlSession session = factory.openSession();
Student s = new Student();
s.setName("小張");
s.setAge(26);
s.setBirthday(new Date());
s.setMoney(5100.0);
try{
session.insert("org.leadfar.Student.insert",s);
session.commit();
}catch(Exception e){
e.printStackTrace();
session.rollback();
}
finally{
session.close();
}
}
public void testupdate() {
SqlSessionFactory factory = null;
Reader reader = null;
try {
reader = Resources.getResourceAsReader("Mybatils.xml");
factory =new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("讀取Mybatils.xml文件失敗");
}
SqlSession session = factory.openSession();
Student s = new Student();
s.setId(1);
s.setName("小sa");
s.setAge(23);
s.setBirthday(new Date());
s.setMoney(6100.20);
try{
session.insert("org.leadfar.Student.update",s);
session.commit();
}catch(Exception e){
e.printStackTrace();
session.rollback();
}
finally{
session.close();
}
}
public void testdelete() {
SqlSessionFactory factory = null;
Reader reader = null;
try {
reader = Resources.getResourceAsReader("Mybatils.xml");
factory =new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("讀取Mybatils.xml文件失敗");
}
SqlSession session = factory.openSession();
Student s = new Student();
s.setId(2);
try{
session.insert("org.leadfar.Student.delete",s);
session.commit();
}catch(Exception e){
e.printStackTrace();
session.rollback();
}
finally{
session.close();
}
}
public void testselectone() {
SqlSession session = factory.openSession(true);
//Student p=(Student)session.selectOne("org.leadfar.Student.selectone",1);
Student p=(Student)session.selectOne(Student.class.getName()+".selectone", 1);
System.out.println(p);
}
}

發佈留言