写在前面——
用 MyBatis 也做过几个项目了,但是一直没有很深入的去理解这个框架,最近决定从头开始学习和整理MyBatis。
之前开发的项目并不是我先创建的,等我介入的时候发现他们已经稍稍封装了一下对MyBatis的使用,反正不是那种官方文档上代码的样子,所以我之前用得就糊里糊涂的,今天就从官方文档中展示的用法开始学习。
正文如下——
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 6 <typeAliases> 7 <typeAlias alias="Book" type="tech.ipush.model.Book" /> 8 </typeAliases> 9 <environments default="development"> 10 <environment id="development"> 11 <transactionManager type="JDBC"/> 12 <dataSource type="POOLED"> 13 <property name="driver" value="com.mysql.cj.jdbc.Driver"/> 14 <property name="url" value="jdbc:mysql://localhost:3306/webpractice?autoReconect=true&useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8"/> 15 <property name="username" value="root"/> 16 <property name="password" value="root"/> 17 </dataSource> 18 </environment> 19 </environments> 20 <mappers> 21 <mapper resource="tech/ipush/mapper/BookMapper.xml" /> 22 </mappers> 23 </configuration>
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 5 <mapper namespace="tech.ipush.mapper.BookMapper"> 6 <select id="getBook" resultType="Book"> 7 select * from book where id=#{id} 8 </select> 9 </mapper>
String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sqlSessionFactory.openSession(); try { Book book1 = (Book) session.selectOne("tech.ipush.mapper.BookMapper.getBook", 2); System.out.println("book1Name: " + book1.getName()); } finally { session.close(); }
public interface BookMapper { Book getBook(int id); }
String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session2 = sqlSessionFactory.openSession(); try { BookMapper mapper = session2.getMapper(BookMapper.class); Book book = mapper.getBook(2); System.out.println("bookName: " + book.getName()); } catch (Exception e) { e.printStackTrace(); } finally { session.close(); }
package tech.ipush.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import tech.ipush.model.Bill;
@Repository @Mapper public interface BillMapper { @Select("select * from bill where id = #{id}") Bill selectBill(int id); }
原文:https://www.cnblogs.com/bityinjd/p/9595641.html