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

 
 
<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> 
         
        <mapper resource="com/test/mybatis/dao/UserDaoMapper.xml"/> 
             
    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 queryUser();
}

对应的UserDaoMapper.xml

 
 
 
<mapper namespace="com.test.mybatis.dao.UserDao"> 
 
 
    <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 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());
        } 

    }
}

你可能感兴趣的:(web应用)