MyBatis 配置

在数据库下建立用户表

CREATE TABLE `user_info` (
  `USER_ID` int(11) NOT NULL AUTO_INCREMENT,
  `USER_NAME` varchar(100) NOT NULL,
  `USER_PWD` varchar(32) NOT NULL,
  PRIMARY KEY (`USER_ID`)
)

1、新建项目导入MyBatis的jar包,连接到什么类型的数据库还需要导入相对应的jar包。

(比如mysql用的是mysql-connector-java-5.1.25-bin.jar)

2、在src下加入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>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://localhost:3306/jeefw" />
				<property name="username" value="root" />
				<property name="password" value="hainan" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="com/huizhi/mapper/UserMapper.xml" />
	</mappers>
</configuration>

3、在src下新建com.huizhi.po包、com.huizhi.mapper包、com.huizhi.test包。

4、在po包下建立实体类

package com.huizhi.po;


public class User {
	
	@Override
	public String toString() {
		return "用户信息 [USER_ID=" + USER_ID + ", USER_NAME=" + USER_NAME + ", USER_PWD=" + USER_PWD + "]";
	}

	private String USER_ID;
	
	private String USER_NAME;
	
	private String USER_PWD;

	public String getUSER_ID() {
		return USER_ID;
	}

	public void setUSER_ID(String uSER_ID) {
		USER_ID = uSER_ID;
	}

	public String getUSER_NAME() {
		return USER_NAME;
	}

	public void setUSER_NAME(String uSER_NAME) {
		USER_NAME = uSER_NAME;
	}

	public String getUSER_PWD() {
		return USER_PWD;
	}

	public void setUSER_PWD(String uSER_PWD) {
		USER_PWD = uSER_PWD;
	}
	
}

5、在com.huizhi.mapper下建立映射文件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">
<mapper namespace="com.huizhi.mapper.UserMapper">
	<select id="selectByUserId" parameterType="String" resultType="com.huizhi.po.User">
		SELECT * FROM user_info WHERE USER_ID = #{USER_ID}
	</select>
</mapper>

6、创建测试类。

InputStream inputStream = Resources.getResourceAsStream("myBatis-config.xml");
SqlSessionFactory SSF = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = SSF.openSession();
			
User syUser = session.selectOne("com.huizhi.mapper.UserMapper.selectByUserId","实质要查询的ID");