关闭

[置顶] Mybatis入门与框架搭建

标签: mybatis搭建
2550人阅读 评论(2) 收藏 举报
分类:

一. Web项目的Mybatis搭建
1. 准备:
① Mybatis的Jar包

mybatis-3.2.8.jar
mysql-connector-java-5.1.30.jar

② 在MySQL中新建表

create table `user`(
`id` varchar(64) NOT NULL COMMENT 'ID',
`name` varchar(255) NOT NULL COMMENT '姓名',
`age` int NOT NULL COMMENT '年龄',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户表';
※数据请自己添加

③ 目录结构
mybatis_config.xml Mybatis配置文件(包括数据库配置,Entity配置,Mapper.XML配置)
mybatis.java 测试类
UserDao.java Dao类
UserEntity.java Entity类
UserMapper.xml Mapper.xml(CRUD的SQL)
web.xml Web项目配置文件
mybatis.jsp ← 测试页面


2. 编写代码
① UserEntity.java

package com.sun.mybatis;

import java.util.UUID;

public class UserEntity {
	
	private String id;	// ID
	private String name;	// 姓名
	private String age;	// 年龄
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	
	/**
	 * 插入之前执行方法,需要手动调用
	 */
	public void preInsert(){
		// 不限制ID为UUID,调用setIsNewRecord()使用自定义ID
		setId(uuid());
	}
	
	/**
	 * 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.
	 */
	public static String uuid() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}
}

② UserDao.java
package com.sun.mybatis;

import java.util.List;

public interface UserDao {

	/**
	 * 获取单条数据
	 * @param id
	 * @return
	 */
	public UserEntity get(String id);
	
	/**
	 * 获取单条数据
	 * @param entity
	 * @return
	 */
	public UserEntity get(UserEntity entity);
	
	/**
	 * 查询数据列表
	 * @param entity
	 * @return
	 */
	public List<UserEntity> findList(UserEntity entity);
	
	/**
	 * 查询
	 * @param entity
	 * @return
	 */
	public List<UserEntity> findAllList(UserEntity entity);
	
	/**
	 * 查询
	 * @see public List<UserEntity> findAllList(UserEntity entity)
	 * @return
	 */
	@Deprecated
	public List<UserEntity> findAllList();
	
	/**
	 * 插入数据
	 * @param entity
	 * @return
	 */
	public int insert(UserEntity entity);
	
	/**
	 * 更新数据
	 * @param entity
	 * @return
	 */
	public int update(UserEntity entity);
	
	/**
	 * 删除数据
	 * @see public int delete(T entity)
	 * @return
	 */
	@Deprecated
	public int delete(String id);
	
	/**
	 * 删除数据
	 * @return
	 */
	public int delete(UserEntity entity);
	
}

③ UserMapper.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">
<mapper namespace="com.sun.mybatis.UserDao">
    
	<sql id="userColumns">
		a.id AS "id",
		a.name AS "name",
		a.age AS "age"
	</sql>
	
	<sql id="userJoins">
	</sql>
    
	<select id="get" resultType="User">
		SELECT 
			<include refid="userColumns"/>
		FROM user a
		<include refid="userJoins"/>
		WHERE a.id = #{id}
	</select>
	
	<select id="findList" resultType="User">
		SELECT 
			<include refid="userColumns"/>
		FROM user a
		<include refid="userJoins"/>
		<where>
			a.del_flag = #{DEL_FLAG_NORMAL}
		</where>
	</select>
	
	<select id="findAllList" resultType="User">
		SELECT 
			<include refid="userColumns"/>
		FROM user a
		<include refid="userJoins"/>
	</select>
	
	<insert id="insert">
		INSERT INTO user(
			id,
			name,
			age
		) VALUES (
			#{id},
			#{name},
			#{age}
		)
	</insert>
	
	<update id="update">
		UPDATE user SET 	
			name = #{name},
			age = #{age}
		WHERE id = #{id}
	</update>
	
	<update id="delete">
		DELETE FROM user
		WHERE id = #{id}
	</update>
	
</mapper>

④ mybatis_config.xml
<?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>  
        <settings>  
            <!-- changes from the defaults -->  
            <setting name="lazyLoadingEnabled" value="false" />  
        </settings>  
        <typeAliases>  
            <!-- 这里给实体类取别名,方便在mapper配置文件中使用 -->
            <typeAlias alias="User" type="com.sun.mybatis.UserEntity"/>
        </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://192.168.3.100:3306/SMPH?useUnicode=true&amp;characterEncoding=utf-8"/>
                    <property name="username" value="root"/>  
                    <property name="password" value="51602966"/>  
                </dataSource>  
            </environment>  
        </environments>  
        <!-- 这里添加的是执行CRUD操作的接口对应的配置文件(xml文件) -->  
        <mappers>
            <mapper resource="com/sun/mybatis/UserMapper.xml"/>
        </mappers>  
    </configuration> 

⑤ web.xml中添加:
	<context-param>
	  <param-name>mybatisConfig</param-name>
	  <param-value>./mybatis_config.xml</param-value>
	</context-param>
因为我放在resource下,所以前面加"./"

⑥ mybatis.java
package com.sun.mybatis;

import java.io.Reader;
import java.util.Map;

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 org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class mybatis{
    
    private UserDao userDao;
	
    Reader reader;

    SqlSessionFactory sessionFactory;  
      
    SqlSession session = null;

    Map<String, String> product;
	
    @SuppressWarnings("deprecation")
    @RequestMapping("/mybatis.do")
    public String getUser(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
    	
    	// Session Factory初期化
    	Initialize(request.getServletContext().getInitParameter("mybatisConfig"));

    	try{
            modelMap.addAttribute("userList", userDao.findAllList());
        }  
        catch (Exception e)  
        {  
            e.printStackTrace();  
        }  
        
        return "/mybatis";
    }
    
    private void Initialize(String configFile){
        try {  
            //1、指定MyBaties配置文件  
            reader = Resources.getResourceAsReader(configFile);
        	
	    //2、创建SqlSessionFactory()  
	    sessionFactory = new SqlSessionFactoryBuilder().build(reader);
              
            session = sessionFactory.openSession();  
              
            userDao = session.getMapper(UserDao.class);
            
        } catch (Exception e) {  
            e.printStackTrace();  
        }
    }
}

⑦ mybatis.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="../jsp/include/taglibs.jsp"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>    
    <title>Mybatis</title>
  </head>
  
  <body>
  	<jsp:include page="/jsp/index.jsp"/>
  	<form:form id="form" name="userList" modelAttribute="userList" action="mybatis.do" method="post" >
	  	<div>
	  		<input type="submit" id="getUser" value="Get User">
	  	</div>
	    <div id='divContext'>
	        <c:forEach items="${userList}" var="user">
	        	<th>ID:${user.id}</th><br>
	        	<th>姓名${user.name}</th><br>
	        	<th>年龄:${user.age}</th><br>
	        	<th>--------------------------------</th><br>
		  	</c:forEach>
	    </div>
  	</form:form>
  </body>
</html>

3. 测试结果:



二. Java项目的Mybatis搭建
1. 准备:
① Mybatis的Jar包

mybatis-3.2.8.jar
mysql-connector-java-5.1.30.jar

② 在MySQL中新建表
<pre name="code" class="sql">create table `user`(
`id` varchar(64) NOT NULL COMMENT 'ID',
`name` varchar(255) NOT NULL COMMENT '姓名',
`age` int NOT NULL COMMENT '年龄',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户表';

※数据请自己添加


③ 目录结构
mybatis_config.xml Mybatis配置文件(包括数据库配置,Entity配置,Mapper.XML配置)
mybatis.java 测试类
UserDao.java Dao类
UserEntity.java Entity类
UserMapper.xml Mapper.xml(CRUD的SQL)


2. 编写代码

① UserEntity.java

package entity;

import java.util.UUID;

public class UserEntity {
	
	private String id;	// ID
	private String name;	// 姓名
	private String age;	// 年龄
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	
	/**
	 * 插入之前执行方法,需要手动调用	 */
	public void preInsert(){
		// 不限制ID为UUID,调用setIsNewRecord()使用自定义ID
		setId(uuid());
	}
	
	/**
	 * 封装JDK自带的UUID, 通过Random数字生成, 中间用-分割.
	 */
	public static String uuid() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}
}

② UserDao.java
package dao;

import java.util.List;

import entity.UserEntity;

public interface UserDao {

	/**
	 * 获取单条数据
	 * @param id
	 * @return
	 */
	public UserEntity get(String id);
	
	/**
	 * 获取单条数据
	 * @param entity
	 * @return
	 */
	public UserEntity get(UserEntity entity);
	
	/**
	 * 查询数据列表
	 * @param entity
	 * @return
	 */
	public List<UserEntity> findList(UserEntity entity);
	
	/**
	 * 查询数据列表
	 * @param entity
	 * @return
	 */
	public List<UserEntity> findAllList(UserEntity entity);
	
	/**
	 * 查询数据列表
	 * @see public List<UserEntity> findAllList(UserEntity entity)
	 * @return
	 */
	@Deprecated
	public List<UserEntity> findAllList();
	
	/**
	 * 插入数据
	 * @param entity
	 * @return
	 */
	public int insert(UserEntity entity);
	
	/**
	 * 更新数据
	 * @param entity
	 * @return
	 */
	public int update(UserEntity entity);
	
	/**
	 * 删除数据
	 * @see public int delete(T entity)
	 * @return
	 */
	@Deprecated
	public int delete(String id);
	
	/**
	 * 删除数据
	 * @return
	 */
	public int delete(UserEntity entity);
	
}

③ UserMapper.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">
<mapper namespace="dao.UserDao">
    
	<sql id="userColumns">
		a.id AS "id",
		a.name AS "name",
		a.age AS "age"
	</sql>
	
	<sql id="userJoins">
	</sql>
    
	<select id="get" resultType="User">
		SELECT 
			<include refid="userColumns"/>
		FROM user a
		<include refid="userJoins"/>
		WHERE a.id = #{id}
	</select>
	
	<select id="findList" resultType="User">
		SELECT 
			<include refid="userColumns"/>
		FROM user a
		<include refid="userJoins"/>
		<where>
			a.del_flag = #{DEL_FLAG_NORMAL}
		</where>
	</select>
	
	<select id="findAllList" resultType="User">
		SELECT 
			<include refid="userColumns"/>
		FROM user a
		<include refid="userJoins"/>
	</select>
	
	<insert id="insert">
		INSERT INTO user(
			id,
			name,
			age
		) VALUES (
			#{id},
			#{name},
			#{age}
		)
	</insert>
	
	<update id="update">
		UPDATE user SET 	
			name = #{name},
			age = #{age}
		WHERE id = #{id}
	</update>
	
	<update id="delete">
		DELETE FROM user
		WHERE id = #{id}
	</update>
	
</mapper>

④ mybatis_config.xml

<?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>  
        <settings>  
            <!-- changes from the defaults -->  
            <setting name="lazyLoadingEnabled" value="false" />  
        </settings>  
        <typeAliases>  
            <!-- 这里给实体类取别名,方便在mapper配置文件中使用 -->
            <typeAlias alias="User" type="entity.UserEntity"/>
        </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://192.168.3.100:3306/SMPH?useUnicode=true&characterEncoding=utf-8"/>  
                    <property name="username" value="root"/>  
                    <property name="password" value="51602966"/>  
                </dataSource>  
            </environment>  
        </environments>  
        <!-- 这里添加的是执行CRUD操作的接口对应的配置文件(xml文件) -->  
        <mappers>
            <mapper resource="mapper/UserMapper.xml"/>
        </mappers>  
    </configuration> 

⑤ mybatis.java

package service;

import java.io.Reader;
import java.util.List;
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 dao.UserDao;
import entity.UserEntity;

public class mybatis{
    
	private static UserDao userDao;
	
	private static Reader reader;

	private static SqlSessionFactory sessionFactory;  
      
	private static SqlSession session = null;
	
    public static void main(String[] args){
    	
    	// Session Factory
    	Initialize("mybatis_config.xml");

    	try{
    		List<UserEntity> userList = userDao.findAllList();
    		
    		for(UserEntity user:userList){
    			System.out.println("ID:" + user.getId());
    			System.out.println("Name:" + user.getName());
    			System.out.println("Age:" + user.getAge());
    		}
        }  
        catch (Exception e)  
        {  
            e.printStackTrace();  
        }
    }
    
    private static void Initialize(String configFile){
        try {  
        	reader = Resources.getResourceAsReader(configFile);
        	
	        sessionFactory = new SqlSessionFactoryBuilder().build(reader);
              
            session = sessionFactory.openSession();  
              
            userDao = session.getMapper(UserDao.class);
            
        } catch (Exception e) {  
            e.printStackTrace();  
        }
    }
}

3. 测试结果:
ID:1
Name:孙
Age:30
ID:2
Name:王
Age:31
ID:3
Name:赵
Age:32

1
3

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:116303次
    • 积分:2120
    • 等级:
    • 排名:第19072名
    • 原创:105篇
    • 转载:18篇
    • 译文:0篇
    • 评论:25条
    文章分类
    最新评论