MyBatis中的全局配置文件

本文详细介绍了在MyBatis框架中如何通过XML和SQL语句进行参数传递,包括单个参数和多个参数的使用方法。同时,文章还讲解了如何处理数据库字段与Java对象属性不一致的情况,通过resultMap实现数据映射。

目录:

  • 如何xml,sql语句传值

  • 返回集合List,resultTYPE为集合中元素类全名

  • 返回单个对象resultTYPE vo类全名

首先先做一些准备工作:

1.配置mybatis.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>
    <environments default="dev">
        <environment id="dev">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/test" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="student.xml"></mapper>
    </mappers>
</configuration>

2.导入jar包

3.把工程建成类似这样

4.创建 Student类

package com.jd.student.vo;

public class Student {

	private String id;
	private String name;
	private String mobile;
	private String address;
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	
}

1.通过一个参数,确定一个对象:

  IStudentDao中:

public interface IStudentDao {
        //getName方法,通过id传参
	String getName(String id);
	
}

student.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">

<mapper namespace="com.jd.student.dao.IStudentDao">

    <select id="getName" resultType="java.lang.String"> //id处写方法名
        select name from stu where id=#{id}
    </select>
</mapper>

Test中:

public class Test {

	public static void main(String[] args) throws Exception {
		InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession sqlSession = sqlSessionFactory.openSession();
		IStudentDao studentDao = sqlSession.getMapper(IStudentDao.class);
                //传入数据库中对象的id
		System.out.println(studentDao.getName("328cc546-03d4-4e90-8b22-1ed66ffac217"));
		sqlSession.close();
	}
}

2.通过两个参数,确定一个对象

  IStudentDao中:

public interface IStudentDao {

        //传多个参数时要加上@Param
	String getName(@Param("id")String id,@Param("mobile")String mobile);
	
}

 student.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">

<mapper namespace="com.jd.student.dao.IStudentDao">

    <select id="getName" resultType="java.lang.String">
        select name from stu where id=#{id} and mobile=#{mobile}
    </select>
</mapper>

Test中: 

public class Test {

	public static void main(String[] args) throws Exception {
		InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession sqlSession = sqlSessionFactory.openSession();
		IStudentDao studentDao = sqlSession.getMapper(IStudentDao.class);
                //传入id,mobile
		System.out.println(studentDao.getName("328cc546-03d4-4e90-8b22-1ed66ffac217","123"));
		sqlSession.close();
	}
}

3.如果数据库和class类不照应:

  IStudentDao中:

public interface IStudentDao {

	List<Student> select(String name);
}

  student.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">

<mapper namespace="com.jd.student.dao.IStudentDao">
	
    <resultMap type="com.jd.student.vo.Student" id="stu">
        <result column="id" property="id"/>    <!-- column是数据库里面的,property是Student类里面的属性 -->
		<result column="user_name" property="name"/>
		<result column="mobile" property="mobile"/>
		<result column="address" property="address"/>
	</resultMap>

    <select id="select" resultMap="stu">
        select id,user_name,mobile,address from student where user_name like #{name}
    </select>

</mapper>

Test中:

public class Test {

	public static void main(String[] args) throws Exception {
		InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession sqlSession = sqlSessionFactory.openSession();
		IStudentDao studentDao = sqlSession.getMapper(IStudentDao.class);
		System.out.println(studentDao.getClass().getName());
		for(Student student:studentDao.select("王%")) {
			System.out.println(student.getName());
		}
		sqlSession.close();
	}
}

 

 

 

 

 

### MyBatis全局配置文件设置方法 MyBatis全局配置文件通常为 `mybatis-config.xml`,该文件包含了全局配置信息,如数据库连接参数、插件等,整个框架只需一个全局配置文件即可[^1]。以下是具体的设置步骤: 1. **属性配置(properties)**:可以加载外部的 Java 资源文件(properties 文件),也可以通过子标签 `property` 设置属性。例如: ```xml <properties resource="db.properties"> <property name="username" value="root"/> <property name="password" value="password"/> </properties> ``` 在使用时,可以通过 `${key}` 来获取设置的属性值。 2. **设置(settings)**:影响 MyBatis 框架在运行时的一些行为,设置缓存、延迟加载、结果集控制、执行器、分页设置、命名规则等一系列控制性参数,与 MyBatis 的运行性能息息相关。所有的 `setting` 配置都被包裹在 `<settings>` 标签对中。示例如下: ```xml <settings> <setting name="logImpl" value="LOG4J"/> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> ``` 3. **类型别名设置(typeAliases)**:为 Java 类型设置别名,简化 XML 配置中的类型引用。示例: ```xml <typeAliases> <typeAlias alias="User" type="com.example.entity.User"/> </typeAliases> ``` 4. **类型处理器(typeHandlers)**:用于自定义 Java 类型和 JDBC 类型之间的转换。示例: ```xml <typeHandlers> <typeHandler handler="com.example.typehandler.MyTypeHandler"/> </typeHandlers> ``` 5. **环境配置(environments)**:配置数据库连接环境,包含事务管理器和数据源的配置。示例: ```xml <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <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> ``` 6. **映射器(mappers)**:指定 SQL 映射文件或接口类,MyBatis 会根据这些映射来执行 SQL 语句。示例: ```xml <mappers> <mapper resource="com/example/mapper/UserMapper.xml"/> <mapper class="com.example.mapper.UserMapper"/> <package name="com.example.mapper"/> </mappers> ``` ### MyBatis全局配置文件的内容结构 MyBatis 全局配置文件的配置顺序有严格要求,如果配置多项,必须按照以下顺序进行配置: 1. `properties`:属性配置 2. `settings`:设置 3. `typeAliases`:类型别名设置 4. `typeHandlers`:类型处理器 5. `environments`:环境配置 - `environment`(环境变量) - `transactionManager`(事务管理器) - `dataSource`(数据源) 6. `mappers`:映射器 ### 完整示例 ```xml <configuration> <properties resource="db.properties"> <property name="username" value="root"/> <property name="password" value="password"/> </properties> <settings> <setting name="logImpl" value="LOG4J"/> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <typeAliases> <typeAlias alias="User" type="com.example.entity.User"/> </typeAliases> <typeHandlers> <typeHandler handler="com.example.typehandler.MyTypeHandler"/> </typeHandlers> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <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> <mapper resource="com/example/mapper/UserMapper.xml"/> </mappers> </configuration> ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值