文章目录
1.搭建Mybatis环境
①拷入jar包
②在MySQL数据库中创建一个user_info表
create table user_info(
id char(36) primary key,
user_name varchar(15) unique,
password varchar(15) not null
)
insert into user_info (id, user_name, password)
values ('3ddcf637-15a8-49d9-a378-b3fa2f2f9c65', 'Aimee', '1983_2560x');
insert into user_info (id, user_name, password)
values ('7eb9deed-ec87-416e-abb3-1a5a2ce819de', 'Cassie', 'xm@560_lq');
2.代码
①创建一个名字为mybitis.xml的普通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>
</configuration>
②在sql的包下创建一个area.xml的普通xml文件,用于存放sql语句
<?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="com.jd.area.IAreaDao"><!-- namespace为接口名 -->
<select id="getName" resultType="java.lang.String">
<!-- id为需要调用的IAreaDao接口中的方法的名字
resultType为调用方法的返回值类型
-->
select user_name from user_info
</select>
</mapper>
③在com.jd的包下创建一个IAreaDao的接口
package com.jd;
public interface IAreaDao {
String getName();
}
④在com.jd.test包下创建一个Test类
package com.jd.test;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.jd.area.IAreaDao;
public class Test {
public static void main(String[] args) throws IOException {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
IAreaDao areaDao = applicationContext.getBean(IAreaDao.class);
System.out.println(areaDao.getClass().getName());
}
}
⑤创建一个Spring Bean Configuration File ,这里命名为“application.xml”
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" value="#{dataSource}"></property>
<property name="configLocation" value="classpath:mybatis.xml"></property>
<property name="mapperLocations" value="classpath:sql/*.xml"></property>
</bean>
<mybatis-spring:scan base-package="com.jd.area"/>
</beans>
⑥运行得到结果
该方法实现了sql语句的分离