Sql建表语句

  1. CREATE TABLE `user` (
  2. `age` int(11) NOT NULL,
  3. `name` varchar(64) NOT NULL DEFAULT '',
  4. `id` int(11) NOT NULL
  5. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

1.原生Api使用

测试用例

  1. package cn.shiyujun.mybatis;
  2. import cn.shiyujun.entity.User;
  3. import org.apache.ibatis.session.SqlSession;
  4. import org.apache.ibatis.session.SqlSessionFactory;
  5. /**
  6. * @author jsf
  7. * @description:
  8. * @date 1/4/2021 10:03 AM
  9. */
  10. public class TestMyBatis {
  11. static SqlSessionFactory sqlSessionFactory = null;
  12. static {
  13. sqlSessionFactory = MyBatisUtil.getSqlSessionFactory();
  14. }
  15. public static void main(String[] args) {
  16. testAdd();
  17. getUser();
  18. }
  19. public static void testAdd() {
  20. SqlSession sqlSession = sqlSessionFactory.openSession();
  21. try {
  22. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  23. User user = new User(1, "lisi", new Integer(25));
  24. userMapper.insertUser(user);
  25. User user2 = new User(2, "zhangsan", new Integer(25));
  26. userMapper.insertUser(user2);
  27. sqlSession.commit();// 这里一定要提交,不然数据进不去数据库中
  28. } finally {
  29. sqlSession.close();
  30. }
  31. }
  32. public static void getUser() {
  33. SqlSession sqlSession = sqlSessionFactory.openSession();
  34. try {
  35. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  36. User user = userMapper.getUser("zhangsan");
  37. System.out.println("name: " + user.getName() + "|age: "
  38. + user.getAge());
  39. } finally {
  40. sqlSession.close();
  41. }
  42. }
  43. }

工具类

  1. public class MyBatisUtil {
  2. private final static SqlSessionFactory sqlSessionFactory;
  3. static {
  4. String resource = "mybatis-config.xml";
  5. Reader reader = null;
  6. try {
  7. reader = Resources.getResourceAsReader(resource);
  8. } catch (IOException e) {
  9. System.out.println(e.getMessage());
  10. }
  11. sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
  12. }
  13. public static SqlSessionFactory getSqlSessionFactory() {
  14. return sqlSessionFactory;
  15. }
  16. }

mybatis-config.xml

  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. <!-- 加载类路径下的属性文件 -->
  7. <properties resource="db.properties">
  8. </properties>
  9. <settings>
  10. <!-- changes from the defaults for testing -->
  11. <setting name="cacheEnabled" value="false" />
  12. <setting name="useGeneratedKeys" value="true" />
  13. <setting name="defaultExecutorType" value="REUSE" />
  14. </settings>
  15. <!-- 设置实体类的类型别名 -->
  16. <typeAliases>
  17. <typeAlias type="cn.shiyujun.entity.User" alias="user"/>
  18. </typeAliases>
  19. <!-- 设置一个默认的连接环境信息,支持多数据源 -->
  20. <environments default="mysql_env">
  21. <!-- 连接环境信息,取一个唯一的编号 -->
  22. <environment id="mysql_env">
  23. <!-- mybatis使用的jdbc事务管理方式 -->
  24. <transactionManager type="jdbc">
  25. </transactionManager>
  26. <!-- mybatis使用连接池方式来获取链接 -->
  27. <dataSource type="pooled">
  28. <!-- 配置与数据库交互的四个属性 -->
  29. <property name="driver" value="${mysql.driver}"/>
  30. <property name="url" value="${mysql.url}"/>
  31. <property name="username" value="${mysql.username}"/>
  32. <property name="password" value="${mysql.password}"/>
  33. </dataSource>
  34. </environment>
  35. </environments>
  36. <mappers>
  37. <mapper resource="mappers/UserMapper.xml"/>
  38. </mappers>
  39. </configuration>

db.properties

  1. mysql.driver=com.mysql.jdbc.Driver
  2. mysql.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false
  3. mysql.username=root
  4. mysql.password=root

UserMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <!-- 名称空间namespace必须唯一 -->
  5. <mapper namespace="cn.shiyujun.mybatis.UserMapper">
  6. <!-- 这里namespace必须是UserMapper接口的路径” -->
  7. <insert id="insertUser" parameterType="User">
  8. insert into user(id,name,age) values(#{id},#{name},#{age})
  9. <!-- 这里sql结尾不能加分号,否则报“ORA-00911”的错误 -->
  10. </insert>
  11. <!-- 这里的id必须和UserMapper接口中的接口方法名相同 -->
  12. <select id="getUser" resultType="User" parameterType="java.lang.String">
  13. select * from user where name=#{name}
  14. </select>
  15. </mapper>

UserMapper

  1. public interface UserMapper {
  2. public void insertUser(User user);
  3. public User getUser(String name);
  4. }

2.Mybatis联合Spring使用

测试用例

  1. public class TestSpringMybatis {
  2. public static void main(String[] args) {
  3. testMapper();
  4. testMapperFactoryBeanMapper();
  5. }
  6. public static void testMapper(){
  7. ApplicationContext context = new ClassPathXmlApplicationContext("classpath:application-mybatis.xml");
  8. //<mybatis:scan> 注入的mapper
  9. UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
  10. User user = userMapper.getUser("zhangsan");
  11. System.out.println("name: " + user.getName() + "|age: " + user.getAge());
  12. }
  13. public static void testMapperFactoryBeanMapper(){
  14. ApplicationContext context = new ClassPathXmlApplicationContext("classpath:application-mybatis.xml");
  15. //MapperFactoryBean 注入的mapper, 获取工厂本事用name &userMapper2
  16. UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
  17. User user = userMapper.getUser("zhangsan");
  18. System.out.println("name: " + user.getName() + "|age: " + user.getAge());
  19. }
  20. }

db.properties、mybatis-config.xml、UserMapper.java、UsreMapper.xml 均和上方一致

application-mybatis.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
  4. xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd"
  6. default-autowire="byName">
  7. <!-- 加载属性资源 -->
  8. <context:property-placeholder location="classpath:/db.properties"></context:property-placeholder>
  9. <!-- 配置 SqlSessionFactoryBean -->
  10. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  11. <property name="dataSource" ref="dataSource" />
  12. <!-- mybatis 配置文件位置(默认配置的话,可以不用)-->
  13. <property name="configLocation" value="classpath:/mybatis-config.xml"></property>
  14. <!-- 配置映射器文件(mybatis-config 中已经配置了) -->
  15. <!-- <property name="mapperLocations" value="classpath:/mappers/UserMapper.xml" />-->
  16. </bean>
  17. <!-- 配置数据源 -->
  18. <!-- 这里使用的是 druid 连接池,需要另外导入 druid.jar -->
  19. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
  20. <property name="driverClassName" value="${mysql.driver}" />
  21. <property name="url" value="${mysql.url}" />
  22. <property name="username" value="${mysql.username}" />
  23. <property name="password" value="${mysql.password}" />
  24. </bean>
  25. <!-- 事务管理器 -->
  26. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  27. <property name="dataSource" ref="dataSource" />
  28. </bean>
  29. <!-- SqlSessionTemplate管理mybatis的qlSession,线程安全,可以被多个DAO所共享使用 -->
  30. <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
  31. <constructor-arg index="0" ref="sqlSessionFactory" />
  32. <!-- 配置了BATCH 表示所有的语句可以批量操作 -->
  33. <constructor-arg index="1" value="BATCH" />
  34. </bean>
  35. <!-- mapper扫描后注入spring容器 -->
  36. <mybatis:scan base-package="cn.shiyujun.mybatis" />
  37. <!-- MapperFactoryBean继承了SqlSessionDaoSupport -->
  38. <bean id="userMapper2" class="org.mybatis.spring.mapper.MapperFactoryBean">
  39. <property name="mapperInterface" value="cn.shiyujun.mybatis.UserMapper" />
  40. <property name="sqlSessionFactory" ref="sqlSessionFactory" />
  41. </bean>
  42. </beans>