1.配置数据源和需要加载的映射文件
<?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">
<!-- 事务提交方式:
JDBC:利用jdbc方式处理事务(commit rollback close)
MANAGED:将事务交由其他组件去托管(spring,jBoss),默认会关闭连接
-->
<transactionManager type="MANAGED"/>
<!-- 数据源类型:
POOLED:使用数据库连接池
UNPOOLED:传统的jdbc模式
JNDI:从tomcat中获取一个内置的数据库连接池
-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/firstdb?serverTimezone=GMT"/>
<property name="username" value="root"/>
<property name="password" value="mysqlpasw"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="yang/text/mapper/personMapper.xml"/>
</mappers>
</configuration>
2.配置映射文件
<?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:该映射文件的唯一标识 -->
<mapper namespace="yang.text.mapper.personMapper">
<select id="queryPersonById" resultType="yang.text.entity.Person" parameterType="int">
select * from person where id = #{id}
</select>
<insert id="addPerson" parameterType="yang.text.entity.Person">
insert into person(id,name,age) values(#{id},#{name},#{age})
</insert>
<update id="updatePerson" parameterType="yang.text.entity.Person">
update person set id = #{id},name = #{name},language = #{age}
</update>
<delete id="deletePersonById" parameterType="int">
delete from person where id = #{id}
</delete>
</mapper>
3.配置映射文件对应的接口
package yang.text.mapper;
import yang.text.entity.Person;
public interface personMapper {
Person queryPersonById(int id);
void addPerson(Person person);
void updatePerson(Person person);
void deletePersonById(int id);
}
4.测试类
package yang.text.entity;
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 yang.text.mapper.personMapper;
import java.io.Reader;
public class myBatisTest {
public static void main(String[] args) throws Exception{
Reader reader = Resources.getResourceAsReader("config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);//可以通过build的第二个参数来改变数据库环境
SqlSession sqlSession = sqlSessionFactory.openSession();
personMapper mapper = sqlSession.getMapper(personMapper.class);
Person person = mapper.queryPersonById(1);
System.out.println(person.toString());
sqlSession.close();
}
}