coding
yu0312chao的gravatar头像
yu0312chao2014-10-03 16:27:12

mybatis新手入门学习项目代码及其框架搭建教程

首先我提供一个中文网站给新手来学习吧!网址:

   http://mybatis.github.io/mybatis-3/zh/index.html

我先把我的项目工程目录展示一下:

我采用的是mysql数据来完成项目的执行的:首先就是完成数据库的处理过程

created database mybatis 
user mybatis
CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `NAME` varchar(20) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

第一种方式我是依赖于配置文件的方式来把整个项目先运行起来,对于mybatis而言,最重要的就是两个配置文件:如我的项目框架中的 mapper.xml 和 mybatisConf.xml

首先我先把mapper.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="net.nyist.firstmybatisdemo.domain.mapper">

  <insert id="insertUser" parameterType="net.nyist.firstmybatisdemo.domain.User">
      insert into users(name,age) values(#{name},#{age})
  </insert>
  
  <select id="selectUser" parameterType="int" resultType="net.nyist.firstmybatisdemo.domain.User">
  
    select * from users where id=#{id}
    
  </select>
</mapper>

然后是mybatisConf.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>   
  <properties resource="dataSource.properties"/>  
      <environments default="development">        
         <environment id="development">        
                 <transactionManager type="jdbc"/>                
                 <dataSource type="pooled">                  
                      <property name="driver" value="${driver}"/>
                      <property name="url" value="${url}"/>
                      <property name="username" value="${username}"/>
                      <property name="password" value="${password}"/>                
                 </dataSource>                   
         </environment>
      </environments>
      <mappers>
          <mapper resource="net/nyist/firstmybatisdemo/domain/mapper.xml"/>
      </mappers>
</configuration>

由于我想给用户带来方便我将我的数据库的配置都放到properties资源文件中:dataSource.properties

url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf-8
username=root
password =root
driver=com.mysql.jdbc.Driver

User实体类的代码展示如下:

package net.nyist.firstmybatisdemo.domain;

import java.io.Serializable;

/**
 * @author yuchao
 * 
 * @school 南阳理工软件学院移动设备应用与开发移动四班
 * 
 * @email yu0312chao@163.com
 * 
 * @time 2014年10月2日 下午7:45:52
 */

@SuppressWarnings("serial")
public class User implements Serializable {

	private int id;
	private String name;
	private int age;

	public User() {
	}

	public User(int id, String name, int age) {

		this.id = id;
		this.name = name;
		this.age = age;
	}

	public User(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public int getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

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

}

测试类 TestFirstMybatisDemo代码展示:

package net.nyist.firstmybatisdemo.test;

import java.io.IOException;
import java.io.InputStream;

import javax.sql.DataSource;

import net.nyist.firstmybatisdemo.domain.BlogMapper;
import net.nyist.firstmybatisdemo.domain.User;
import net.nyist.mybatis.datasource.yuchao.BlogDataSourceFactory;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

/**
 * @author yuchao
 *
 * @school 南阳理工软件学院移动设备应用与开发移动四班
 *
 * @email yu0312chao@163.com
 *
 * @time  2014年10月2日 下午7:56:43
 */

public class TestFirstMybatisDemo {
   
	 public static void main(String[] args) {
		    
		    try {
				InputStream inputStream = Resources.getResourceAsStream("mybatisConf.xml");
				SqlSessionFactory sessionFactory  =new SqlSessionFactoryBuilder().build(inputStream);
				SqlSession session = sessionFactory.openSession(true);
				User user =new User("余超", 21);
				String statement ="net.nyist.firstmybatisdemo.domain.mapper"+".insertUser";
				int i =session.insert(statement,user);
				if (i==1) 	
			             System.out.println("新增加用户成功!!!!");
			         else
			              System.out.println("添加用户失败!!!");
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
  }

运行结果为:

第二种方式是基于注解的:注解方式增加一个接口类BlogMapper代码展示如下

package net.nyist.firstmybatisdemo.domain;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;

/**
 * @author yuchao
 *
 * @school 南阳理工软件学院移动设备应用与开发移动四班
 *
 * @email yu0312chao@163.com
 *
 * @time  2014年10月2日 下午8:56:16
 */

public interface BlogMapper {
     
	 @Insert("insert into users(name, age) values(#{name}, #{age})")
	 public int insertUser(User user);
	 
	 @Select("select * from users where id=#{id}")
	 public User selectUser(int id);
}

只需要一个配置文件: mybatisConf.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>   
  <properties resource="dataSource.properties"/>  
      <environments default="development">        
         <environment id="development">        
                 <transactionManager type="jdbc"/>                
                 <dataSource type="pooled">                  
                      <property name="driver" value="${driver}"/>
                      <property name="url" value="${url}"/>
                      <property name="username" value="${username}"/>
                      <property name="password" value="${password}"/>                
                 </dataSource>                   
         </environment>
      </environments>
      <mappers>
              <mapper class="net.nyist.firstmybatisdemo.domain.BlobMapper"/>
      </mappers>
</configuration>

测试类 TestFirstMybatisDemo代码如下:

package net.nyist.firstmybatisdemo.test;

import java.io.IOException;
import java.io.InputStream;

import javax.sql.DataSource;

import net.nyist.firstmybatisdemo.domain.BlogMapper;
import net.nyist.firstmybatisdemo.domain.User;
import net.nyist.mybatis.datasource.yuchao.BlogDataSourceFactory;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

/**
 * @author yuchao
 *
 * @school 南阳理工软件学院移动设备应用与开发移动四班
 *
 * @email yu0312chao@163.com
 *
 * @time  2014年10月2日 下午7:56:43
 */

public class TestFirstMybatisDemo {
   
	 public static void main(String[] args) {
		    
		  annotationMethod();
		
	}
	public static void annotationMethod() {
			try {
				InputStream inputStream = Resources.getResourceAsStream("mybatisConf.xml");
				SqlSessionFactory sessionFactory  =new SqlSessionFactoryBuilder().build(inputStream);
				SqlSession session = sessionFactory.openSession(true);
				BlogMapper userMapper =session.getMapper(BlogMapper.class);
				User user2 =userMapper.selectUser(1);
				System.out.println(user2.getName());
				session.close();
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
}

运行结果:

第三种方式:完全摆脱xml文件束缚,全部采用注解的方式

相对于第二种方式的代码不改,就是对于测试代码的更改:TestFirstMybatisDemo.java

package net.nyist.firstmybatisdemo.test;

import java.io.IOException;
import java.io.InputStream;

import javax.sql.DataSource;

import net.nyist.firstmybatisdemo.domain.BlogMapper;
import net.nyist.firstmybatisdemo.domain.User;
import net.nyist.mybatis.datasource.yuchao.BlogDataSourceFactory;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

/**
 * @author yuchao
 *
 * @school 南阳理工软件学院移动设备应用与开发移动四班
 *
 * @email yu0312chao@163.com
 *
 * @time  2014年10月2日 下午7:56:43
 */

public class TestFirstMybatisDemo {
   
	 public static void main(String[] args) {
		    
		 // annotationMethod();
		  testNoMapper();
	}
	public static void annotationMethod() {
			try {
				InputStream inputStream = Resources.getResourceAsStream("mybatisConf.xml");
				SqlSessionFactory sessionFactory  =new SqlSessionFactoryBuilder().build(inputStream);
				SqlSession session = sessionFactory.openSession(true);
				BlogMapper userMapper =session.getMapper(BlogMapper.class);
				User user2 =userMapper.selectUser(1);
				System.out.println(user2.getName());
				session.close();
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	public static void testNoMapper(){
		   
		  DataSource dataSource =BlogDataSourceFactory.getBlogDataSource();
		  TransactionFactory transactionFactory =new JdbcTransactionFactory();		  
		  Environment environment =new Environment("development", transactionFactory,dataSource);
		  Configuration configuration =new Configuration(environment);
		  configuration.addMapper(BlogMapper.class);
		  SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(configuration);
		  SqlSession session = sessionFactory.openSession(true);
		  User user = session.selectOne("net.nyist.firstmybatisdemo.domain.BlogMapper.selectUser", 3);
		  if (user!=null) 
		       System.out.println("用户的姓名:"+user.getName());
		  System.out.println("对不起,您所要查找的用户不存在!!!!");
		  session.close();
	}
}

运行结果:

第一种情况:

第二种情况:


打赏

文件名:firstmybatisdemo.zip,文件大小:1249.953K下载
  • /
      • /firstmybatisdemo
顶部客服微信二维码底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友