赞
踩
1.User类
package com.itheima.domain; import java.io.Serializable; import java.util.Date; public class User implements Serializable{ private Integer userId; private String userName; private Date userBirthday; private String userSex; private String userAddress; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Date getUserBirthday() { return userBirthday; } public void setUserBirthday(Date userBirthday) { this.userBirthday = userBirthday; } public String getUserSex() { return userSex; } public void setUserSex(String userSex) { this.userSex = userSex; } public String getUserAddress() { return userAddress; } public void setUserAddress(String userAddress) { this.userAddress = userAddress; } @Override public String toString() { return "User{" + "userId=" + userId + ", userName='" + userName + '\'' + ", userBirthday=" + userBirthday + ", userSex='" + userSex + '\'' + ", userAddress='" + userAddress + '\'' + '}'; } }
2.IUser接口
package com.itheima.dao; import com.itheima.domain.User; import com.sun.xml.internal.bind.v2.model.core.ID; import org.apache.ibatis.annotations.*; import java.util.List; public interface IUserDao { //查询所有用户 @Select("select * from user") @Results(id = "userMap", value = { @Result(id=true,column="id",property="userId"), @Result(column="username",property="userName"), @Result(column="sex",property="userSex"), @Result(column="address",property="userAddress"), @Result(column="birthday",property="userBirthday") }) List<User> getAllUsers(); /* 根据用户id查询用户信息 */ @Select("select * from user where id = #{uid}") @ResultMap("userMap") User findUserById(Integer uId); /* 保存用户信息 */ @Insert("insert into user(username,sex,birthday,address) values(#{userName},#{userSex},#{userBirthday},#{userAddress})") @SelectKey(keyColumn="id",keyProperty="userId",resultType=Integer.class,before = false, statement = { "select last_insert_id()" }) int saveUser(User user); /** * 更新操作 * @param user * @return */ @Update("update user set\n" + "username=#{userName},address=#{userAddress},sex=#{userSex},birthday=#{userBirthday} where id\n" + "=#{userId} ") int updateUser(User user); /* 删除操作 */ @Delete("delete from user where id=#{uId}") int deleteUser(Integer uId); @Select("select count(*) from user") int countTotal(); /* 模糊查询 */ @Select("Select * from user where username like #{username}") @ResultMap("userMap") List<User> findByName(String name); }
3.配置文件
<?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"> <!---第三步 写 mybatis主配置文件 --> <configuration> <!--mysql外部配置文件路径--> <properties url="file:///D:\IdeaProjects\mybatis05\src\main\resources\jdbcConfig.properties"> </properties> <!--配置参数 --> <settings> <!--开启mybatis支持延迟加载--> <setting name="lazyLoadingEnabled" value="true"/> <setting name="aggressiveLazyLoading" value="false"></setting> </settings> <!--取别名--> <typeAliases> <!-- 批量别名定义,扫描整个包下的类,别名为类名(首字母大写或小写都可以) --> <package name="com.itheima.domain"/> </typeAliases> <!-- 配置环境--> <environments default="mysql"> <!-- 配置mysql的环境--> <environment id="mysql"> <!-- 配置事务--> <transactionManager type="JDBC"></transactionManager> <!--配置连接池 使用配置文文件外部读取的方式--> <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> <!-- 配置 dao 接口的位置,它有两种方式 注解开发 第一种:使用 mapper 标签配置 class 属性 第二种:使用 package 标签,直接指定 dao 接口所在的包 --> <package name="com.itheima.dao"/> </mappers> </configuration>
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatisLearn
jdbc.username=root
jdbc.password=root
4.测试代码
package com.itheima.test; import com.itheima.dao.IUserDao; import com.itheima.domain.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.InputStream; import java.util.Date; import java.util.List; /** * 第六步 测试mybatis的curd操作 */ public class UserTest { private static InputStream in; private static SqlSession sqlSession; private static IUserDao userDao; /** * 初始化函数 */ @Before public void init() throws Exception { //1.读取配置文件,生成字节输入流 in = Resources.getResourceAsStream("SqlMapConfig.xml"); //2.获取SqlSessionFactory SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); //3.获得SqlSession对象 sqlSession = factory.openSession(); //4.获取dao的代理对象 userDao = sqlSession.getMapper(IUserDao.class); } /** * 最后执行 * * @throws Exception */ @After public void finallys() throws Exception { //提交事务 sqlSession.commit(); //6.关闭连接 释放资源 sqlSession.close(); in.close(); } /** * 测试查询所有数据功能 */ @Test public void testFindAll() { //5.执行查询方法 List<User> users = userDao.getAllUsers(); for (User u : users) { System.out.println("-------每个用户的内容---------"); System.out.println(u.toString()); } } /** * 测试根据id查询 */ @Test public void testFindUserById() { //5.执行查询方法 User user = userDao.findUserById(41); System.out.println(user); } /** * 测试插入数据 */ @Test public void testSaveUser() { User user = new User(); user.setUserName("安抚"); user.setUserSex("女"); user.setUserBirthday(new Date()); user.setUserAddress("江西赣州"); int r = userDao.saveUser(user); if(r>0){ System.out.println("保存成功!"); } } /** * 测试更新数据 */ @Test public void testUpdateUser() { User user = new User(); user.setUserId(50); user.setUserName("123"); user.setUserSex("男"); user.setUserBirthday(new Date()); user.setUserAddress("江2州"); int r = userDao.updateUser(user); if(r>0){ System.out.println("更新成功!"); } } /** * 测试删除数据 通过注解方式,我们就不需要再去编写 UserDao.xml 映射文件了。 */ @Test public void testDeleteUser() { int r = userDao.deleteUser(51); if(r>0){ System.out.println("删除成功!"); } } /** * 测试模糊查询 */ @Test public void testFindUserByName() { List<User> userList = userDao.findByName("%王%"); int count = userDao.countTotal(); System.out.println(count); for (User u : userList) { System.out.println(u.toString()); } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。