01 - 搭建mybatis工程

1 工程创建

2 导包

<dependencies>
   <dependency>
       <groupId>org.mybatis</groupId>
       <artifactId>mybatis</artifactId>
       <version>3.5.6</version>
   </dependency>
   <dependency>
       <groupId>mysql</groupId>
       <artifactId>mysql-connector-java</artifactId>
       <version>8.0.19</version>
   </dependency>
   <dependency>
       <groupId>junit</groupId>
       <artifactId>junit</artifactId>
       <version>4.13</version>
       <scope>test</scope>
   </dependency>
</dependencies>

3 创建核心配置文件

如果在idea中创建配置文件需要加载resources目录下

注意:如果使用mysql8版本链接多个参数,使用*&amp;*链接(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.cj.jdbc.Driver"/>
               <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC "/>
               <property name="username" value="root"/>
               <property name="password" value="123456"/>
           </dataSource>
       </environment>
   </environments>
   <mappers>
       <mapper resource="cn/laixueit/pojo/UserMapper.xml"/>
   </mappers>
</configuration>

4 创建数据库

5 创建实体类

6 创建实体类映射文件

创建接口文件

public interface UserMapper {

   public List<User> findAll();

   public User findById(Integer id);
}
<?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="org.mybatis.example.BlogMapper">
   <select id="selectBlog" resultType="cn.laixueit.entity.User">
       select * from user
   </select>

   <select id="selectOne" resultType="cn.laixueit.entity.User">
       select * from user where id =#{id}
   </select>
</mapper>

7 测试

@Test
public void selectList() throws IOException {
   InputStream stream = Resources.getResourceAsStream("mybatis.xml");
   SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
   SqlSession session = sqlSessionFactory.openSession();
   List<Object> list = session.selectList("org.mybatis.example.BlogMapper.selectBlog");
   System.out.println(list);
}

@Test
public void selectOne() throws IOException {
   InputStream stream = Resources.getResourceAsStream("mybatis.xml");
   SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
   SqlSession session = sqlSessionFactory.openSession();
   User u = session.selectOne("org.mybatis.example.BlogMapper.selectOne",41);
   System.out.println(u);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值