MyBatisUtil.java
UserMapper.java
package edu.hhxy.btais.util; import java.io.IOException; import java.io.InputStream; 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 MyBatisUtil { private static SqlSession session = null; public static SqlSession createSeqSession() { try { // 1、创建配置文件(mybatis-config.xml)的输入流 InputStream is = Resources .getResourceAsStream("mybatis-config.xml"); // 2、创建SQLSessionFactory SqlSessionFactory factory = new SqlSessionFactoryBuilder() .build(is); // 3、创建SQLSessioin session = factory.openSession(); } catch (IOException e) { e.printStackTrace(); } return session; } public static void closeSeqSession(SqlSession sqlSession) { try { sqlSession.close(); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession = null; } } }
jdbc.properties
1
2
3
4 |
username=root password=root url=jdbc:mysql: //localhost:3306/mybatis driver=com.mysql.jdbc.Driver |
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> <properties resource="jdbc.properties" /> <typeAliases> <package name="edu.hhxy.btais" /> </typeAliases> <!-- 在properties之后加上typeAliases --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <!-- 配置mybatis的pooled的数据源 --> <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> <package name="edu.hhxy.btais"/> </mappers> </configuration>
TestMybatisByMapperAnnotation
package edu.hhxy.btais; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import edu.hhxy.btais.mapper.UserMapper; import edu.hhxy.btais.util.MyBatisUtil; public class TestMybatisByMapperAnnotation { @Test public void addTest() { SqlSession session = null; try { session = MyBatisUtil.createSeqSession(); User u = new User(); u.setNickname("猪八戒"); u.setPassword("123"); u.setType(1); u.setUsername("bajie"); session.getMapper(UserMapper.class).add(u); session.commit(); } catch (Exception e) { e.printStackTrace(); } finally { MyBatisUtil.closeSeqSession(session); } } }
只需要了解即可。
mybatis(基于annotation的方法知道就行了),布布扣,bubuko.com
原文:http://www.cnblogs.com/jianfengyun/p/3722051.html