从 XML 中构建 SqlSessionFactory
每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为中心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先定制的 Configuration 的实例构建出 SqlSessionFactory 的实例。
从 XML 文件中构建 SqlSessionFactory 的实例,建议使用类路径下的资源文件进行配置。但是也可以使用任意的输入流(InputStream)实例,包括字符串形式的文件路径或者 file:// 的 URL 形式的文件路径来配置。MyBatis 包含一个名叫 Resources 的工具类,它包含一些实用方法,可使从 classpath 或其他位置加载资源文件更加容易。
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
XML 配置文件(configuration XML)中包含了对 MyBatis 系统的核心设置,包含获取数据库连接实例的数据源(DataSource)和决定事务作用域和控制方式的事务管理器(TransactionManager)。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>
<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:///school?useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="qwer1234"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
存放sql语句的xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.aa">
<select id="selectStudent" resultType="study.study.bean.User">
select * from student
</select>
</mapper>
用配置的xml从数据库取信息
package study
/**
* Created by Administrator on 2017/10/10.
*/
public class MyTest {
public static void main(String[
![Uploading 10111_195338.jpg . . .]
] args) throws Exception{
InputStream is= Resources.getResourceAsStream("mybatis-config.xml");
//获取主配置文件
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
//创建工厂对象
SqlSession sqlSession=factory.openSession();
//获取sqlsession(相当于connection)
List<User> list=sqlSession.selectList("selectStudent");
//当返回的是list是用selectlist
//当返回的只是一个对象的时候用selectone
//修改操作时用update
//新增用insert
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
}
}
补充一下
SqlSession sqlSession=factory.openSession(true);
//获取sqlsession(相当于connection)当设置为true时,开启自动提交事物
//在对数据库有改动的时候要提交事物才会生效
int update=sqlSession.update("com.aa.updateStudent",user);
sqlSession.commit();
//提交
System.out.println(update);
sqlSession.close();
//选择true的时候就不需要自己手动提交了
10-11
之前是在测试类中用sqlsession执行xml文件的sql语句,对数据库进行操作,反正不好。。。。
先定义一接口可以看做项目中的dao层
//接口
public interface GoodsMapper {
Goods selectGoodsById();
List<Goods> selectGoodsAll();
int insertGoods(Goods goods);
int updateGoods(Goods goods);
}
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//获取主配置文件
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//创建工厂对象
SqlSession sqlSession = factory.openSession(true);
//获取sqlsession(相当于connection)true意思是自动提交事物
GoodsMapper mapper = sqlSession.getMapper(GoodsMapper.class);
//通过实现类拿到接口---这里是接口对象
Goods goods = new Goods();
goods.setGname("黄瓜");
int a = mapper.insertGoods(goods);
//用接口调用里面的方法
System.out.println(a);
sqlSession.close();
描述sql语句的xml文件
<mapper namespace="com.study.mapper.GorderMapper">
<!--
1 namespace 与接口全限定名一致
2 id和抽象函数保持一致
3 参数类型与返回类型保持一致
4 Java类名与xml文件名保持一致
-->
<select id="selectGorderAll" resultType="Gorder">
select * from gorder
</select>//select标签
<insert id="insertGorder" parameterType="Gorder">
insert into gorder (orderId,createTime,status,price,uid,gid) VALUES (#
{orderId},now(),#{status},#{price},#{uid},#{gid})
</insert>//insert标签
<update id="updateGorder" parameterType="Gorder">//parameterType参数类型
update Gorder set price = #{price} where orderId = #{orderId}
</update>//update标签
<delete id="removeGorder" parameterType="Gorder">
delete FROM gorder where orderId = #{orderId}
</delete>//delete标签
</mapper>
mybatis-config.xml配置
将原来存于mybatis-config.xml里的jdbc的配置文件放于一个properties下面
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///taobao?useUnicode=true&characterEncoding=utf-8
jdbc.user=root
jdbc.password=qwer1234
在mybatis-config.xml引用properties文件内容
<properties resource="jdbc.properties"></properties>
后面的使用properties信息
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClass}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
setting 配置
<settings>
<!-- 日志的实现类,可以不写,会自动匹配 -->
<setting name="logImpl" value="LOG4J"/>
<!-- 将数据库字段的下划线自动转为驼峰命名 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 自动映射,FULL表示无论是否关联都进行自动映射 -->
<setting name="autoMappingBehavior" value="FULL"/>
</settings>
配置log4j---->日志是在console上输出的一些内部信息,比如执行了哪些sql
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.study.mapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
别名
resultType参数返回类型,只写类名简写,在config.xml配置
<typeAliases>
<package name="com.study.bean"></package>//这里是另bean下面的都可以用别名
</typeAliases>
<!-- 使用的使用直接使用别名Goods,不用写全限定名 -->com.bean.Goods
<select id="selectGoodsById" resultType="Goods">
select * from goods where gid=3
</select>
输入映射 parameterType--->
config.xml和存sql 的xml关联起来
<mappers>
<mapper resource="UserMapper.xml"/>
<mapper resource="GoodsMapper.xml"/>
<mapper resource="GorderMapper.xml"/>
</mappers>
后面还有两个关联。。。log4j没写