MyBatis入门基本的配置介绍
MyBatis入门基本的配置介绍
小贱是个程序员 发表于2年前
MyBatis入门基本的配置介绍
  • 发表于 2年前
  • 阅读 20
  • 收藏 0
  • 点赞 0
  • 评论 0

移动开发云端新模式探索实践 >>>   

工具:Eclipse

首先下载Mabatis所需要的jar包,导包

 

然后配置mybatis核心文件取名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>
	<properties resource="jdbc_mysql.properties"/>
	
	<!-- 和spring整合后 environments配置将废除-->
	<environments default="development">
		<environment id="development">
		<!-- 使用jdbc事务管理-->
			<transactionManager type="JDBC" />
		<!-- 数据库连接池-->
			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driver}" />
				<property name="url" value="${jdbc.url}" />
				<property name="username" value="${jdbc.username}" />
				<property name="password" value="${jdbc.password}" />
			</dataSource>
		</environment>
	</environments>
	
	<mappers>
		<mapper resource="User.xml"/>
	</mappers>

</configuration>

然后配置连接数据库的资源文件,取名 jdbc_mysql.properties,取名要有意义

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123

然后配置日志文件,也就是查询时输出SQL语句

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

然后创建一个实体User

package cn.web.entity;

import java.util.Date;

public class User {
	private int id;
	private String username;// 用户姓名
	private String sex;// 性别
	private Date birthday;// 生日
	private String address;// 地址
	
	
	public User() {
		super();
	}
	public User(int id, String username, String sex, Date birthday, String address) {
		super();
		this.id = id;
		this.username = username;
		this.sex = sex;
		this.birthday = birthday;
		this.address = address;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address="
				+ address + "]";
	}
	
	
}

然后就是Mybatis关键的一步了配置实体映射的查询语句

<?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="cn.web">


  <select id="findUserid" parameterType="int" resultType="cn.web.entity.User">
  	SELECT * FROM USER WHERE id = #{id}
  </select>
  
  <select id="findUname" parameterType="String" resultType="cn.web.entity.User">
  	SELECT * FROM USER WHERE username LIKE #{username}
  	<!-- SELECT * FROM USER WHERE username LIKE concat('%',#{username},'%') -->
  	<!-- SELECT * FROM USER WHERE username LIKE '%' #{username} '%' -->
  </select>
  
  <delete id="deleteByid" parameterType="int">
		delete from User where id=#{id}  	
  </delete>
  
  <insert id="insert" parameterType="cn.web.entity.User">
  	<selectKey databaseId="id" order="AFTER">
  		SELECT LAST_INSERT_ID()
  	</selectKey>
  	INSERT INTO USER (id,username,sex,birthday,address) VALUES (#{id},#{username},#{sex},#{birthday},#{address})
  </insert>
  
  <update id="update" parameterType="cn.web.entity.User">
  	UPDATE USER SET username=#{username} WHERE id=#{id} 
  </update>
  
  
</mapper>

最后编写一个数据连接的MybatisUtil,用来连接数据库

package cn.web.entity;

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;

public  class MyBatisUtil {
	
	private static SqlSessionFactory sqlSessionFactory;
	
	public static SqlSession getSqlSession(){
		try {
			InputStream is = Resources.getResourceAsStream("mybatis.xml");
			if(sqlSessionFactory == null){
				sqlSessionFactory=new SqlSessionFactoryBuilder().build(is);
			}
			return sqlSessionFactory.openSession();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}

最后一步编写Test测试文件

package cn.web.entity;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


public class Test {
	@org.junit.Test
	public void testName() throws Exception {
		//mybatis配置文件
		String resource ="mybatis.xml" ;
		//得到流对象
		InputStream inputStream = Resources.getResourceAsStream(resource) ;
		//创建会话工厂
		SqlSessionFactory ssf=new SqlSessionFactoryBuilder().build(inputStream);
		//通过会话工厂得到会话
		SqlSession sqs= ssf.openSession();
		//通过会话创建数据库
		User user=sqs.selectOne("cn.web.findUserid",40);
		System.out.println(user);
		//List<User> list= sqs.selectList("cn.web.findUname", "张"+"%");
		//sqs.insert("cn.web.insert",new User(40,"Make","2",new Date(),"珠海"));
		//sqs.update("cn.web.update", new User(40,"小杨",null,null,null));
		//sqs.delete("cn.web.deleteByid",30);
		//SELECT LAST_INSERT_ID()
		sqs.commit();
		//关闭会话
		sqs.close();
	}
	
}

测试成功通过

标签: MyBatis Java EE MySQL
  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 3
博文 29
码字总数 9960
×
小贱是个程序员
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: