Sql建表语句
CREATE TABLE `user` (
`age` int(11) NOT NULL,
`name` varchar(64) NOT NULL DEFAULT '',
`id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1.原生Api使用
测试用例
package cn.shiyujun.mybatis;
import cn.shiyujun.entity.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
/**
* @author jsf
* @description:
* @date 1/4/2021 10:03 AM
*/
public class TestMyBatis {
static SqlSessionFactory sqlSessionFactory = null;
static {
sqlSessionFactory = MyBatisUtil.getSqlSessionFactory();
}
public static void main(String[] args) {
testAdd();
getUser();
}
public static void testAdd() {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = new User(1, "lisi", new Integer(25));
userMapper.insertUser(user);
User user2 = new User(2, "zhangsan", new Integer(25));
userMapper.insertUser(user2);
sqlSession.commit();// 这里一定要提交,不然数据进不去数据库中
} finally {
sqlSession.close();
}
}
public static void getUser() {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUser("zhangsan");
System.out.println("name: " + user.getName() + "|age: "
+ user.getAge());
} finally {
sqlSession.close();
}
}
}
工具类
public class MyBatisUtil {
private final static SqlSessionFactory sqlSessionFactory;
static {
String resource = "mybatis-config.xml";
Reader reader = null;
try {
reader = Resources.getResourceAsReader(resource);
} catch (IOException e) {
System.out.println(e.getMessage());
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
}
public static SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
}
mybatis-config.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>
<!-- 加载类路径下的属性文件 -->
<properties resource="db.properties">
</properties>
<settings>
<!-- changes from the defaults for testing -->
<setting name="cacheEnabled" value="false" />
<setting name="useGeneratedKeys" value="true" />
<setting name="defaultExecutorType" value="REUSE" />
</settings>
<!-- 设置实体类的类型别名 -->
<typeAliases>
<typeAlias type="cn.shiyujun.entity.User" alias="user"/>
</typeAliases>
<!-- 设置一个默认的连接环境信息,支持多数据源 -->
<environments default="mysql_env">
<!-- 连接环境信息,取一个唯一的编号 -->
<environment id="mysql_env">
<!-- mybatis使用的jdbc事务管理方式 -->
<transactionManager type="jdbc">
</transactionManager>
<!-- mybatis使用连接池方式来获取链接 -->
<dataSource type="pooled">
<!-- 配置与数据库交互的四个属性 -->
<property name="driver" value="${mysql.driver}"/>
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mappers/UserMapper.xml"/>
</mappers>
</configuration>
db.properties
mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false
mysql.username=root
mysql.password=root
UserMapper.xml
<?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="cn.shiyujun.mybatis.UserMapper">
<!-- 这里namespace必须是UserMapper接口的路径” -->
<insert id="insertUser" parameterType="User">
insert into user(id,name,age) values(#{id},#{name},#{age})
<!-- 这里sql结尾不能加分号,否则报“ORA-00911”的错误 -->
</insert>
<!-- 这里的id必须和UserMapper接口中的接口方法名相同 -->
<select id="getUser" resultType="User" parameterType="java.lang.String">
select * from user where name=#{name}
</select>
</mapper>
UserMapper
public interface UserMapper {
public void insertUser(User user);
public User getUser(String name);
}
2.Mybatis联合Spring使用
测试用例
public class TestSpringMybatis {
public static void main(String[] args) {
testMapper();
testMapperFactoryBeanMapper();
}
public static void testMapper(){
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:application-mybatis.xml");
//<mybatis:scan> 注入的mapper
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
User user = userMapper.getUser("zhangsan");
System.out.println("name: " + user.getName() + "|age: " + user.getAge());
}
public static void testMapperFactoryBeanMapper(){
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:application-mybatis.xml");
//MapperFactoryBean 注入的mapper, 获取工厂本事用name &userMapper2
UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
User user = userMapper.getUser("zhangsan");
System.out.println("name: " + user.getName() + "|age: " + user.getAge());
}
}
db.properties、mybatis-config.xml、UserMapper.java、UsreMapper.xml 均和上方一致
application-mybatis.xml
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
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"
default-autowire="byName">
<!-- 加载属性资源 -->
<context:property-placeholder location="classpath:/db.properties"></context:property-placeholder>
<!-- 配置 SqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- mybatis 配置文件位置(默认配置的话,可以不用)-->
<property name="configLocation" value="classpath:/mybatis-config.xml"></property>
<!-- 配置映射器文件(mybatis-config 中已经配置了) -->
<!-- <property name="mapperLocations" value="classpath:/mappers/UserMapper.xml" />-->
</bean>
<!-- 配置数据源 -->
<!-- 这里使用的是 druid 连接池,需要另外导入 druid.jar -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="${mysql.driver}" />
<property name="url" value="${mysql.url}" />
<property name="username" value="${mysql.username}" />
<property name="password" value="${mysql.password}" />
</bean>
<!-- 事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- SqlSessionTemplate管理mybatis的qlSession,线程安全,可以被多个DAO所共享使用 -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
<!-- 配置了BATCH 表示所有的语句可以批量操作 -->
<constructor-arg index="1" value="BATCH" />
</bean>
<!-- mapper扫描后注入spring容器 -->
<mybatis:scan base-package="cn.shiyujun.mybatis" />
<!-- MapperFactoryBean继承了SqlSessionDaoSupport -->
<bean id="userMapper2" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="cn.shiyujun.mybatis.UserMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
</beans>