MyBatis使用,MyBatis单独使用笔记http://www.bieryun.com/3348.html
1. 创建一张表
2. 引入jar包
3. 创建数据库属性文件db.properties
- jdbc.driver=com.mysql.jdbc.Driver
- jdbc.url=jdbc:mysql://localhost:3306/zhjsdb?characterEncoding=UTF-8
- jdbc.username=root
- jdbc.password=root
4. 创建SqlMapConfig.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="db.properties" />
- <typeAliases>
- <!-- 别名定义 -->
- <!-- 单个别名定义 type:类型的路径 alias:别名 -->
- <!-- <typeAlias type="cn.czy.mybatis.po.User" alias="user"/> -->
- <typeAlias type="com.jx.pojo.User" alias="user" />
- <!-- 批量别名定义 指定包名,mybatis自动扫描包中的po类,自动定义别名 -->
- <package name="com.jx.sqlMapper" />
- </typeAliases>
- <environments default="development">
- <environment id="development">
- <transactionManager type="JDBC" />
- <dataSource type="POOLED">
- <property name="driver" value="${jdbc.driver}" />
- <property name="url" value="${jdbc.url}" />
- <property name="username" value="${jdbc.username}" />
- <property name="password" value="${jdbc.password}" />
- </dataSource>
- </environment>
- </environments>
- <mappers>
- <mapper resource="com/jx/sqlMapper/userMapper.xml"/>
- </mappers>
- </configuration>
- 5. 创建测试类
- package com.jx.sx;
- 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;
- import org.junit.Test;
- import com.jx.pojo.User;
- public class TestMyBatis {
- public SqlSessionFactory getSqlSessionFactory() throws IOException{
- //myBatis 配置文件
- String source = "SqlMappingConfig.xml";
- //得到配置文件流
- InputStream inputStream = Resources.getResourceAsStream(source);
- SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
- inputStream.close();
- return factory;
- }
- @Test
- public void findUserByIdTest() throws IOException {
- SqlSession session = this.getSqlSessionFactory().openSession();
- User user = session.selectOne("test.findUserById",1);
- System.out.println(user);
- session.close();
- }
- /*public static void main(String[] args) throws IOException {
- new TestMyBatis().findUserByIdTest();
- }*/
- }
@Test可能因为版本错误导致报错
换一种方式导入JUnit的包,一般Eclipse会自带JUnit的库,在工程名上点击右键,选择:
bulid path——Add Library,然后显示如下:
选择JUnit添加就行了,再次运行test方法,成功。