mybatis入门

来到YSB(拼音缩写)的RK(拼音缩写)公司实训,当然实际上是暂待两天,在这里先了解了下mybatis框架。
mybatis是一个比较轻量级的持久层框架,与hibernate不同,一些SQL代码要自己写,数据库表也要自己建。
下面是我第一次使用的过程。

这里使用的是mybatic-3.2.1+mysql。
1、首先download到所需的包并加入工程:
http://www.vdisk.cn/down/index/12447775。这是我打包上传的,包括所必须的mytabic-3.2.1.jar,cglib-2.2.2.jar,asm-3.3.1.jar,mysql-connector-java-5.0.8-bin.jar。

2、编写实体类User bean
entity/User.java
package entity;

import java.io.Serializable;

public class User implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3363120264501521428L;

	private String id;
	private String username;
	private String password;
	private String email;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	@Override
	public String toString() {
		return "User [email=" + email + ", id=" + id + ", password=" + password
				+ ", username=" + username + "]";
	}
}


3、User实体的映射器UserMapper,它是一个接口,不需要去实现。
dao/UserMapper.java
package dao;

import java.util.List;

import entity.User;

/**
 * @author Administrator
 * 
 */
public interface UserMapper {
	/**
	 * 查询所有用户
	 * 
	 * @return
	 */
	public List<User> queryUsers();

	/**
	 * 添加用户
	 * 
	 * @param user
	 */
	public void addUser(User user);

	/**
	 * 删除用户
	 * 
	 * @param id
	 */
	public void delUser(String id);

}


4、映射器对应的配置文件
dao/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="dao.UserMapper">
	<!-- 插入用户 -->
	<insert id="addUser" parameterType="User" >
		INSERT INTO t_user(
		id,
		username,
		password,
		email)
		VALUES(
		#{id},
		#{username},
		#{password},
		#{email})
	</insert>
	<!-- 删除用户 -->
	<delete id="delUser" parameterType="String">
		DELETE FROM t_user WHERE id =
		#{id}
	</delete>
	<!-- 列出用户 -->
	<select id="queryUsers" resultType="User">
		SELECT * FROM t_user
	</select>
</mapper>


5、Mybatis的配置文件:
resource/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>
	<settings>
		<setting name="cacheEnabled" value="false" />
		<setting name="useGeneratedKeys" value="true" />
		<setting name="defaultExecutorType" value="REUSE" />
	</settings>
	<typeAliases>
		<typeAlias alias="User" type="entity.User" />
	</typeAliases>
	<environments default="development">
		<environment id="development">
			<transactionManager type="jdbc"></transactionManager>
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://localhost:3306/mybatic" />
				<property name="username" value="root" />
				<property name="password" value="Geek147852" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="dao/UserMapper.xml" />
	</mappers>
</configuration>


6、获取SqlSessionFactory的工具类
util/MybatisUtil.java
/*  
 * MybaticUtil.java            Project:HelloMybatis  
 * Date:2013-3-1
 *  
 * Copyright (c) 2013 CFuture09, Institute of Software,   
 * Guangdong Ocean University, Zhanjiang, GuangDong, China.  
 * All rights reserved.  
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");  
 *  you may not use this file except in compliance with the License.  
 * You may obtain a copy of the License at  
 *  
 *     http://www.apache.org/licenses/LICENSE-2.0  
 *  
 * Unless required by applicable law or agreed to in writing, software  
 * distributed under the License is distributed on an "AS IS" BASIS,  
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
 * See the License for the specific language governing permissions and  
 * limitations under the License.  
 */

package util;

import java.io.IOException;
import java.io.Reader;

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

/**
 * 
 * @author Geek_Soledad ([email protected])
 */

public class MybatisUtil {

	private static final SqlSessionFactory sessionFactory;
	static {
		String resource = "resource/mybatis-config.xml";
		Reader reader = null;
		try {
			reader = Resources.getResourceAsReader(resource);
		} catch (IOException e) {
			e.printStackTrace();
		}
		sessionFactory = new SqlSessionFactoryBuilder().build(reader);
	}

	public static SqlSessionFactory getSessionFactory() {
		return sessionFactory;
	}
}


7、测试代码
dao/UserMapperTest.java
/*  
 * UserMapperTest.java            Project:HelloMybatis  
 * Date:2013-3-1
 *  
 * Copyright (c) 2013 CFuture09, Institute of Software,   
 * Guangdong Ocean University, Zhanjiang, GuangDong, China.  
 * All rights reserved.  
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");  
 *  you may not use this file except in compliance with the License.  
 * You may obtain a copy of the License at  
 *  
 *     http://www.apache.org/licenses/LICENSE-2.0  
 *  
 * Unless required by applicable law or agreed to in writing, software  
 * distributed under the License is distributed on an "AS IS" BASIS,  
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
 * See the License for the specific language governing permissions and  
 * limitations under the License.  
 */

package dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import util.MybatisUtil;
import entity.User;


/** 
 *
 * @author Geek_Soledad ([email protected])
 */

public class UserMapperTest {
	public static SqlSessionFactory sessionFactory = MybatisUtil.getSessionFactory();

	public SqlSession session;

	private UserMapper userMapper;
	
	@Before
	public void openSession() {
		session = sessionFactory.openSession();
		userMapper = session.getMapper(UserMapper.class);
	}
	
	@After
	public void commitAndcloseSession() {
		session.commit();
		session.close();
	}
	@Test
	public void testAddUser() {
		User user = new User();
		user.setEmail("[email protected]");
		user.setUsername("Geek");
		user.setPassword("Soledad");
		userMapper.addUser(user);
	}
	
	@Test
	public void testDelUser() {
		userMapper.delUser("2");
	}
	
	@Test
	public void testQueryUsers() {
		List<User> users = userMapper.queryUsers();
		for (User user : users) {
			System.out.println(user.toString());
		}
	}
}


注:本次入门参考自博客:http://wanqiufeng.blog.51cto.com/409430/515132。本文亦依此而写。

你可能感兴趣的:(java,mysql,mybatis)