核心配置文件
<?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文件-->
<properties resource="jdbc.properties"/>
<!--自定义别名,在mapper里用到,可定义多个-->
<typeAliases>
<typeAlias type="com.domain.Student" alias="student"></typeAlias>
</typeAliases>
<!--环境-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<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="Mapper.xml"/>
</mappers>
</configuration>
mapper
<?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="Mapper">
<insert id="save" parameterType="com.domain.Student">
INSERT INTO student(name,math,eng) VALUES (#{name},#{math}, #{eng})
</insert>
<select id="findAll" resultType="student">
select * from student
</select>
<update id="update" parameterType="student">
update student set name=#{name}, math=#{math}, eng=#{eng} where id =#{id}
</update>
<delete id="delete" parameterType="java.lang.Integer">
delete from student where id=#{id}
</delete>
</mapper>
查询示例
@Test
public void test1() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("Config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
List<Student> list = sqlSession.selectList("Mapper.findAll");
Iterator it = list.iterator();
while (it.hasNext()){
System.out.println(it.next());
}
sqlSession.close();
}
删除示例
//删除
@Test
public void test4() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("Config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
sqlSession.update("Mapper.delete",21);
//提交事务 增删改必须
sqlSession.commit();
sqlSession.close();
}
//更新
@Test
public void test3() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("Config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
Student student = new Student(10,"铁蛋",100,100);
sqlSession.update("Mapper.update",student);
//提交事务 增删改必须
sqlSession.commit();
sqlSession.close();
}