mybatis入门

    

mybatis介绍

    

                    MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。  

                    MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注 SQL 本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等jdbc繁杂的过程代码

                   

   入门程序

                   一:创建一个java工程;

                    二:加入jar包

                        2.1:mybatis-3.2.7.jar----mybatis的核心包

                        2.2:mysql-connector-java-517-bin.jar ----数据驱动包

                        2.3:其它为依赖包

            

                三:classpath下(src)创建log4j.properties如下:      

        mybatis默认使用log4j作为输出日志信息。

# 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

    四:在classpath下(src)创建SqlMapConfig.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>
    <!-- 和spring整合后 environments配置将废除 -->
    <environments default="development">
        <environment id="development">
            <!-- 使用jdbc事务管理 -->
            <transactionManager type="JDBC" />
            <!-- 数据库连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url"
                    value="jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="sqlmap/Usermapper.xml"/>
    </mappers>
</configuration>

SqlMapConfig.xmlmybatis核心配置文件,上边文件的配置内容为数据源、事务管理。

                五: 创建pojo类,与数据库表对应如下:

  数据库:

         

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) NOT NULL COMMENT '用户名称',
  `birthday` date DEFAULT NULL COMMENT '生日',
  `sex` char(1) DEFAULT NULL COMMENT '性别',
  `address` varchar(256) DEFAULT NULL COMMENT '地址',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8;

pojo类:

public class User {
    private Integer id;
    private String username;// 用户姓名
    private String sex;// 性别
    private Date birthday;// 生日
    private String address;// 地址

get/set……
                六: sql映射文件

        

classpath下的sqlmap目录下创建sql映射文件User.xml

        

namespace:命名空间,用于隔离sql,还有一个很重要的作用,下一章会讲   
<?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="test">

</mapper>
    

准备工作完毕,下面开始增删改查


添加:

        在User.xml中添加

<insert id="insertUser" parameterType="domain.User">
		<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
			SELECT LAST_INSERT_ID()
		</selectKey>
		INSERT INTO USER(username,birthday,sex,address) 
			VALUES(#{username},#{birthday},#{sex},#{address})
	</insert>

添加selectKey实现将主键返回

keyProperty:返回的主键存储在pojo中的哪个属性

orderselectKey的执行顺序,是相对与insert语句来说,由于mysql的自增原理执行完insert语句之后才将主键生成,所以这里selectKey的执行顺序为after

resultType:返回的主键是什么类型

LAST_INSERT_ID():mysql的函数,返回auto_increment自增列新记录id


  

创建测试类:    

    

	@Test
	public void testInsert() {
		// 数据库会话实例
		SqlSession sqlSession = null;
		try {
			// 创建数据库会话实例sqlSession
			sqlSession = sqlSessionFactory.openSession();
			// 添加用户信息
			User user = new User();
			user.setUsername("小明");
			user.setAddress("河南");
			user.setSex("1");
			user.setPrice(1999.9f);
			sqlSession.insert("test.insertUser", user);
			//提交事务
			sqlSession.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (sqlSession != null) {
				sqlSession.close();
			}
		}
	}
    

 Mysql使用 uuid实现主键

 

需要增加通过select uuid()得到uuid

<insert id="insertUser" parameterType="mybatis.po.User">

<selectKey resultType="java.lang.String" order="BEFORE"keyProperty="id">

    select uuid()

</selectKey>

insert into user(id,username,birthday,sex,address)

 values(#{id},#{username},#{birthday},#{sex},#{address})

</insert>

注意这里使用的order是“BEFORE


删除:

        在User.xml中添加

<!-- 删除用户 -->
	<delete id="deleteUserById" parameterType="int">
		delete from user where id=#{id}
	</delete>

    创建测试方法:    

    

	//会话工厂
	private SqlSessionFactory sqlSessionFactory;

	@Before
	publicvoid createSqlSessionFactory() throws IOException {
		// 配置文件
		String resource = "SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);

		// 使用SqlSessionFactoryBuilder从xml配置文件中创建SqlSessionFactory
		sqlSessionFactory = new SqlSessionFactoryBuilder()
				.build(inputStream);

	}


// 根据id删除用户
	@Test
	public void testDelete() {
		// 数据库会话实例
		SqlSession sqlSession = null;
		try {
			// 创建数据库会话实例sqlSession
			sqlSession = sqlSessionFactory.openSession();
			// 删除用户
			sqlSession.delete("test.deleteUserById",18);
			// 提交事务
			sqlSession.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (sqlSession != null) {
				sqlSession.close();
			}
		}
	}

修改:

        在User.xml中添加

<!-- 更新用户 -->
	<update id="updateUser" parameterType="mybatis.po.User">
		update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address}
		where id=#{id}
	</update>


    创建测试方法:    

    

	//会话工厂
	private SqlSessionFactory sqlSessionFactory;

	@Before
	publicvoid createSqlSessionFactory() throws IOException {
		// 配置文件
		String resource = "SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);

		// 使用SqlSessionFactoryBuilder从xml配置文件中创建SqlSessionFactory
		sqlSessionFactory = new SqlSessionFactoryBuilder()
				.build(inputStream);

	}


// 更新用户信息
	@Test
	public void testUpdate() {
		// 数据库会话实例
		SqlSession sqlSession = null;
		try {
			// 创建数据库会话实例sqlSession
			sqlSession = sqlSessionFactory.openSession();
			// 添加用户信息
			User user = new User();
			user.setId(16);
			user.setUsername("小明");
			user.setAddress("河南郑州");
			user.setSex("1");
			user.setPrice(1999.9f);
			sqlSession.update("test.updateUser", user);
			// 提交事务
			sqlSession.commit();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (sqlSession != null) {
				sqlSession.close();
			}
		}
	}

  

查询(根据id查询:):

        在User.xml中添加

<!-- 根据id获取用户信息 -->
	<select id="findUserById" parameterType="int"resultType="mybatis.po.User">
		select * from user where id = #{id}
	</select>

parameterType:定义输入到sql中的映射类型,#{id}表示使用preparedstatement设置占位符号并将输入变量id传到sql

resultType定义结果映射类型。

    创建测试方法:    

  

	// 根据 id查询用户信息
	@Test
	public void testFindUserById() {
		// 数据库会话实例
		SqlSession sqlSession = null;
		try {
			// 创建数据库会话实例sqlSession
			sqlSession = sqlSessionFactory.openSession();
			// 查询单个记录,根据用户id查询用户信息
			User user = sqlSession.selectOne("test.findUserById", 10);
			// 输出用户信息
			System.out.println(user);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (sqlSession != null) {
				sqlSession.close();
			}
		}

	}
}

   查询(根据用户名查询:):

        在User.xml中添加

<!-- 自定义条件查询用户列表 -->
	<select id="findUserByUsername" parameterType="java.lang.String"
			resultType="mybatis.po.User">
	   select * from user where username like '%${value}%' 
	</select>

parameterType:定义输入到sql中的映射类型,${value}表示使用参数将${value}替换,做字符串的拼接。

注意:如果是取简单数量类型的参数,括号中的值必须为value

resultType定义结果映射类型。


    创建测试方法:   

// 根据用户名称模糊查询用户信息
	@Test
	publicvoid testFindUserByUsername() {
		// 数据库会话实例
		SqlSession sqlSession = null;
		try {
			// 创建数据库会话实例sqlSession
			sqlSession = sqlSessionFactory.openSession();
			// 查询单个记录,根据用户id查询用户信息
			List<User> list = sqlSession.selectList("test.findUserByUsername", "张");
			System.out.println(list.size());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (sqlSession != null) {
				sqlSession.close();
			}
		}

	}





        





发布了24 篇原创文章 · 获赞 3 · 访问量 1万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章