- mybatis的配置:
0.mybatis和jdbc的jar包
1.基础配置config.xml(里面写上数据库驱动名,url,用户名和密码)
2.把表和类对应起来的xml(须在config.xml里面配置resource) - 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>
<environments default="development">
<!--environment可以配置多个环境,指定运行时计算机的数据库环境,方便程序移植-->
<environment id="development">
<!--事务提交方式:
JDBC:利用jdbc方式处理事务(commit rollback close)
MANAGED:将事务交给其他组件去托管(spring,jboss),默认会关闭连接
-->
<transactionManager type="JDBC"/>
<!--数据源类型:POOLED是使用数据库连接池,UNPOOLED是传统的jdbc方式,
JNDI是从tomcat中获取一个内置的数据库连接池-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/project"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--这里是配置具体表-类映射的xml文件-->
<mapper resource="filetest.xml"/>
</mappers>
</configuration>
-具体表-类映射的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">
<!--namespace:该xml文件的唯一标识符>
<!-建议是一个实体写一个xml文件-->
<mapper namespace="org.entity.Attach">
<!--通过namespace.id来定位该sql-->
<select id="queryAttachByNumber" resultType="org.entity.Attach" parameterType="int">
select * from filetest where number = #{id}<!--这里的id只是占位符,写成什么都无所谓-->
</select>
<!--values里面的参数,如果parameterType是简单类型则随便写,如果是对象则必须是属性名-->
<insert id = "addAttach" parameterType = "org.entity.Attach">
insert into filetest(name,number) values (#{name},#{number})
</insert>
<update id="updateAttachByNum" parameterType="org.entity.Attach">
update filetest set name = #{name},number = #{number}
</update>
<!--不管返回值是一个对象还是多个对象都这么写-->
<select id="queryAllAttaches" resultType="org.entity.Attach">
select * from filetest
</select>
</mapper>
- 测试的java类
public class mybatistest {
public static void main(String args[]){
try{
//把xml文件从硬盘中读成一个resource文件
Reader r= Resources.getResourceAsReader("baseConfig.xml");
//产生SqlSession对象,通过该对象来操作mybatis
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(r);
SqlSession session = sessionFactory.openSession();
//
String statement1 = "org.entity.Attach.queryAttachByNumber";
String statement2 = "org.entity.Attach.queryAllAttaches";
String statement3 = "org.entity.Attach.addAttach";
Attach a = session.selectOne(statement1, 2);
System.out.println(a.getName());
Attach b = new Attach();
b.setId(3);
b.setName("thirdfile");
session.insert(statement3,b);
List<Attach> attaches = session.selectList(statement2);
System.out.println(attaches);
}catch (Exception e){
e.printStackTrace();
}
}
}