目录
3 mybatis配置:mybatis-config.xml
1 前言
本文供以下文章参考使用:
本文顺序在文章:
之后。其中的项目代码,在该文基础上进行了扩充,如果根据本文代码无法正确构建自己的测试环境,请先学习spring相关知识后再来。
2 spring配置:beans.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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 自动创建单例 -->
<bean id="personDao" class="com.evenif.dao.impl.PersonMysqlDaoImpl"/>
<!-- <bean id="aalog" class="com.evenif.log.AnnotationAspectLog"/>-->
<!-- 自动创建单例服务依赖注入已存在dao -->
<bean id="personService" class="com.evenif.service.impl.PersonServiceImpl">
<property name="personDao" ref="personDao"></property>
</bean>
<!-- 配置aop自动扫描使用注解,生产环境中推荐 -->
<!-- <aop:aspectj-autoproxy/>-->
</beans>
3 mybatis配置: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"/>
<typeAliases>
<!-- 别名方式一:给全类名指定别名,可以在mapper映射文件中简化引用-->
<!--
<typeAlias type="com.evenif.bean.Index" alias="Index"/>
-->
<!-- 别名方式二:给包下所有类名指定别名,默认别名是对应的类名-->
<package name="com.evenif.bean"/>
</typeAliases>
<!-- environments指mybatis可以配置多个环境 default指向默认的环境
每个SqlSessionFactory对应一个环境environment -->
<environments default="development">
<environment id="development">
<!-- JDBC - 这个配置直接使用JDBC的提交和回滚功能。它依赖于从
数据源获得连接来管理事务的生命周期。
MANAGER - 这个配置基本上什么都不做。它从不提交或者回滚一个连接
的事务。而是让容器(例如:Spring或者J2EE应用服务器)来管理事务
的生命周期-->
<transactionManager type="JDBC"/>
<!-- 数据源类型:
UNPOOLED - 这个类型的数据源实现只是在每次需要的时候简单地打
开和关闭连接。
POOLED - 这个数据源的实现缓存了JDBC连接对象,用于避免每次创
建新的数据库连接时都初始化和连接认证,加快程序响应。并发WEB应
用通常通过这种做法来获得快速响应。
JNDI - 这个数据源的配置是为了准备与像Spring或应用服务器能够在
外部或者内部配置数据-->
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 配置javaBean对应的mapper文件的位置-->
<mapper resource="PersonMapper.xml"/>
</mappers>
</configuration>
4 mapper配置:PersonMapper.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命名空间 防止sql语句的id重名
namespace命名:包名+类名+mapper文件名
parameterType : sql语句参数类型
resultType: 返回结果类型
userGeneratedKeys="true" 使用自增主键 -->
<mapper namespace="PersonMapper">
<resultMap id="PersonMap" type="com.evenif.bean.Person">
<id column="c_id" property="id"/>
<result column="c_name" property="name"/>
<result column="c_age" property="age"/>
</resultMap>
<!-- 一个小技巧,可以将公共的语句提出来使用<include refid="Base_Column"/>来引用
建议使用该方法:不用select *,如果增删数据库字段,使用*自动匹配会报错,如果使用该方法
如果数据库新加字段,原项目不受影响(新加字段不生效)-->
<sql id="Alias_Base_Column">
c_id id,c_name name,c_age age
</sql>
<sql id="Base_Column">
c_id ,c_name ,c_age
</sql>
<!-- #################### 结果集映射(推荐)#################### -->
<select id="getById" resultMap="PersonMap">
select
<include refid="Base_Column"/>
from t_person where c_id=#{id}
</select>
<!-- 在mybatis-config.xml已经给com.evenif.bean包下的所有类指定了别名,依然可以使用全类名,不影响-->
<select id="loadAll" resultMap="PersonMap">
select
<include refid="Base_Column"/>
from t_person
</select>
<!-- #################### 给列名起别名解决列名和属性名不一致 #################### -->
<select id="getById0" resultType="com.evenif.bean.Person">
select
<include refid="Alias_Base_Column"/>
from t_person where c_id=#{id}
</select>
<!-- 在mybatis-config.xml已经给com.evenif.bean包下的所有类指定了别名,依然可以使用全类名,不影响-->
<select id="loadAll0" resultType="com.evenif.bean.Person">
select
<include refid="Alias_Base_Column"/>
from t_person
</select>
</mapper>
5 bean:
package com.evenif.bean;
public class Person {
int id;
String name;
int age;
public Person() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
6 dao:
package com.evenif.dao;
import com.evenif.bean.Person;
import java.util.List;
public interface PersonDao {
/*
使用给列名起别名的方式解决属性名与类名不一致
*/
Person getById(int id);
List<Person> loadAll();
/*
设置结果集解决属性名与类名不一致
*/
Person getById0(int id);
List<Person> loadAll0();
}
7 daoimpl:
package com.evenif.dao.impl;
import com.evenif.bean.Person;
import com.evenif.dao.PersonDao;
import com.evenif.mybatis.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class PersonMysqlDaoImpl implements PersonDao {
@Override
public Person getById(int id) {
try (SqlSession session = MybatisUtil.getSession()) {
Person person = session.selectOne("PersonMapper.getById", id);
return person;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @return
*/
@Override
public List<Person> loadAll() {
try (SqlSession session = MybatisUtil.getSession()) {
List<Person> list = session.selectList("PersonMapper.loadAll");
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @param id
* @return
*/
@Override
public Person getById0(int id) {
try (SqlSession session = MybatisUtil.getSession()) {
Person person = session.selectOne("PersonMapper.getById0", id);
return person;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @return
*/
@Override
public List<Person> loadAll0() {
try (SqlSession session = MybatisUtil.getSession()) {
List<Person> list = session.selectList("PersonMapper.loadAll0");
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
8 service:
package com.evenif.service;
import com.evenif.bean.Person;
import java.util.List;
public interface PersonService {
Person getPerson(int id);
List<Person> loadPersonList();
Person getPerson0(int id);
List<Person> loadPersonList0();
}
9 serviceImpl:
package com.evenif.service.impl;
import com.evenif.bean.Person;
import com.evenif.dao.PersonDao;
import com.evenif.service.PersonService;
import java.util.List;
public class PersonServiceImpl implements PersonService {
private PersonDao personDao;
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
public PersonServiceImpl() {
}
public PersonServiceImpl(PersonDao personDao) {
this.personDao = personDao;
}
@Override
public Person getPerson(int id) {
return personDao.getById(id);
}
@Override
public List<Person> loadPersonList() {
return personDao.loadAll();
}
@Override
public Person getPerson0(int id) {
return personDao.getById0(id);
}
@Override
public List<Person> loadPersonList0() {
return personDao.loadAll0();
}
}
10 主测试类main:
package com.evenif;
import com.evenif.bean.Person;
import com.evenif.service.PersonService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.IOException;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
PersonService service = (PersonService) context.getBean("personService");
{
System.out.println("使用结果集映射查询一条记录:");
Person person = service.getPerson(1);
System.out.println(person);
}
{
System.out.println("使用结果集映射查询所有记录:");
List<Person> list = service.loadPersonList();
System.out.println(list);
}
{
System.out.println("给列名起别名查询一条记录:");
Person person = service.getPerson0(1);
System.out.println(person);
}
{
System.out.println("给列名起别名查询所有记录:");
List<Person> list = service.loadPersonList0();
System.out.println(list);
}
}
}
//执行结果:
//使用结果集映射查询一条记录:
// Person{id=1, name='张三', age=13}
//使用结果集映射查询所有记录:
// [Person{id=1, name='张三', age=13}, Person{id=2, name='李四', age=14}, Person{id=3, name='王五', age=15}]
//给列名起别名查询一条记录:
// Person{id=1, name='张三', age=13}
//给列名起别名查询所有记录:
// [Person{id=1, name='张三', age=13}, Person{id=2, name='李四', age=14}, Person{id=3, name='王五', age=15}]
11 mybatisUtil:
package com.evenif.mybatis;
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 java.io.IOException;
import java.io.InputStream;
public class MybatisUtil {
public static SqlSession getSession() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
return sqlSessionFactory.openSession();
}
}