您的位置:首页 > 其它

mybatis入门 建议参考mybatis文档

2018-04-03 23:06 357 查看

1.第一步:创建java工程 

使用eclipse创建java工程,jdk使用1.7.0_72。

2.第二步:加入jar包

加入mybatis核心包、依赖包、数据驱动包。



3. 第三步:log4j.properties(mybatis默认使用log4j作为输出日志信息。)

配置如下:
# Global logging configurationlog4j.rootLogger=DEBUG, stdout# Console output...log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
4.第四步:mybatis核心配置文件 SqlMapConfig.xml(必须在classpath下
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><!-- 和spring整合后 environments配置将废除--><environments default="development"><environment id="development"><!-- 使用jdbc事务管理--><transactionManager type="JDBC" /><!-- 数据库连接池--><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" /><property name="username" value="root" /><property name="password" value="root" /></dataSource></environment></environments><mappers><mapper resource="sqlMapper.xml"/></mappers></configuration>

5.第五步:po类 

po类通常与数据库表对应(这里使用用户实体类User.java)

6.第六步:sql映射文件(在classpath下建立sqlMapper.xml)

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="test">
<!-- 根据id获取用户信息 --><select id="findUserById" parameterType="int" resultType="cn.itcast.mybatis.po.User">select * from user where id = #{id}</select></mapper>

7.第七步:测试程序

public class Mybatis_first {//会话工厂private SqlSessionFactory sqlSessionFactory;@Beforepublic void createSqlSessionFactory() throws IOException {// 配置文件String resource = "SqlMapConfig.xml";InputStream inputStream = Resources.getResourceAsStream(resource);// 使用SqlSessionFactoryBuilder从xml配置文件中创建SqlSessionFactorysqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);}// 根据 id查询用户信息@Testpublic void testFindUserById() {// 数据库会话实例SqlSession sqlSession = null;try {// 创建数据库会话实例sqlSessionsqlSession = sqlSessionFactory.openSession();// 查询单个记录,根据用户id查询用户信息User user = sqlSession.selectOne("test.findUserById", 10);// 输出用户信息System.out.println(user); } catch (Exception e) {e.printStackTrace();} finally {if (sqlSession != null) {sqlSession.close();}}}}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: