1. 程式人生 > >servlet+mybatis 整合web工程

servlet+mybatis 整合web工程

之前使用servlet+jdbc搭建web工程,現在通過jmybatis框架在持久化

jar包
mybatis-3.4.6.jar;
mysql-connector-java-5.1.21.jar

工程
1、配置mybatis配置檔案mybatis-config.xml (包含配置datasource+mapper)
mybatis事務型別有兩種:jdbc和managed(web容器管理事務)
關於mybatis如何實現事務,參考這個帖子,說的挺詳細:

https://blog.csdn.net/masusan/article/details/70835062

<?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="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true"/> <property name="username" value
="root" />
<property name="password" value="123456" /> </dataSource> </environment> </environments> <mappers> <!-- 對映檔案方式1,一個一個的配置 --> <mapper resource="com/test/mybatis/dao/UserDaoMapper.xml"/> <!-- 對映檔案方式2,自動掃描包內的Mapper介面與配置檔案 <package name="com/songci/mybatis/mapper"/>--> </mappers> </configuration>

持久化介面(UserDao.java)

/**
 * 
 */
package com.test.mybatis.dao;

import java.util.List;
import com.test.mybatis.domain.User;

/**
 * @author 44306
 *
 */
public interface UserDao 
{
    List<User> queryUser();
}

對應的UserDaoMapper.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"> 
<!-- 首先來解析 namespace: 名稱空間,此屬性通常用來對映Dao層介面. --> 
<mapper namespace="com.test.mybatis.dao.UserDao"> 
<!-- id: 對應Dao層介面方法名 parameterType:指定輸入引數型別 --> 
<!-- useGeneratedKeys="true"把新增加的主鍵賦值到自己定義的keyProperty(id)中 --> 
    <select id="queryUser" resultType="com.test.mybatis.domain.User">
        select * from Users 
    </select>
 </mapper>

實體類(User.java)

/**
 * 
 */
package com.test.mybatis.domain;

/**
 * @author 44306
 *
 */
public class User 
{
    private String id;

    private String userName;

    private String passwd;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPasswd() {
        return passwd;
    }

    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", userName=" + userName + ", passwd="
                + passwd + "]";
    }



}

控制層類(HelloServlet.java)

/**
 * 
 */
package com.test.mybatis.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

import com.test.mybatis.dao.UserDao;
import com.test.mybatis.domain.User;

/**
 * @author 44306
 *
 */
@WebServlet(name="testServlet", urlPatterns={"/test/testServlet"},loadOnStartup=1)
public class HelloServlet extends HttpServlet
{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;



    public void doGet(HttpServletRequest request,HttpServletResponse resp)
    {
        // 1、讀取配置檔案
        String resource = "mybatis-config.xml"; 
        URL o = Thread.currentThread().getContextClassLoader().getResource("");
        String path = o.getPath().replace("classes", "config"); 


        InputStream inputStream;
        try {
            inputStream = new FileInputStream(new File(path+resource));

            // 2、根據配置檔案建立SqlSessionFactory

            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            // 3、SqlSessionFactory建立SqlSession
            /** *2: 從mybatis 資料連線池中獲取 session連線 * 並選擇相應的介面類《mapper》 */ 
            //如果sqlsessionFactory.opensession(true)引數是布林值,如果設定為true,就不需要commit提交事務了
            SqlSession session = sqlSessionFactory.openSession(); 
            UserDao sutdentDao = (UserDao) session.getMapper(UserDao.class); 
            List<User> list = sutdentDao.queryUser();
            System.out.println(list.get(0).toString());
            //3:提交事務 僅在【儲存資料 刪除資料 更新資料】 
            session.commit(); 
            //4:關閉session連線 ---放回至mybatis維護連線池中
            session.close();
        } catch (IOException e) {
            System.out.println("報錯啦!!"+e.getMessage());
        } 

    }
}