mybatis框架学习实验一
建立项目后,需要在mysql数据库中创建一个名为mybatis的数据库,并建立user表
1.创建配置文件 mybatis.cfg.xml
其中<typeAliases>以及<mappers>为后面新增的
<?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> <typeAliases> <!-- 指定一个包名起别名,将包内的 Java 类的类名作为类的类别名 --> <package name="com.zoey.mybatis.model" /> </typeAliases> <!-- 配置mybatis运行环境 --> <environments default="development"> <environment id="development"> <!-- type="JDBC" 代表直接使用 JDBC 的提交和回滚设置 --> <transactionManager type="JDBC" /> <!-- POOLED 表示支持JDBC数据源连接池 --> <!-- 数据库连接池,由 Mybatis 管理,数据库名是 mybatis,MySQL 用户名 root,密码为空 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mybatis" /> <property name="username" value="root" /> <property name="password" value="" /> </dataSource> </environment> </environments> <mappers> <!-- 通过 mapper 接口包加载整个包的映射文件 --> <package name="com/zoey/mybatis/mapper" /> </mappers> </configuration>
2.创建实体类
package com.zoey.mybatis.model; public class User { private Integer id; private String username; private String password; private String sex; private String address; public Integer getId() { return id; } public void setId(Integer 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 getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
3.创建方法接口和定义映射文件
新建方法接口 UserMapper.java ,提供简单的增删改查数据操作。
UserMapper 接口的代码如下:
package com.zoey.mybatis.mapper; import java.util.List; import com.zoey.mybatis.model.User; public interface UserMapper { public int insertUser(User user) throws Exception; public int updateUser(User user) throws Exception; public int deleteUser(Integer id) throws Exception; public User selectUserById(Integer id) throws Exception; public List<User> selectAllUser() throws Exception; }
定义映射文件UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.zoey.mybatis.mapper.UserMapper"> <!-- 自定义返回结果集 --> <resultMap id="userMap" type="User"> <id property="id" column="id" javaType="int"></id> <result property="username" column="username" javaType="String"></result> <result property="password" column="password" javaType="String"></result> <result property="sex" column="sex" javaType="String"></result> <result property="address" column="address" javaType="String"></result> </resultMap> <!-- 定义 SQL 语句,其中 id 需要和接口中的方法名一致 --> <!-- useGeneratedKeys:实现自动生成主键 --> <!-- keyProperty: 唯一标记一个属性 --> <!-- parameterType 指明查询时使用的参数类型,resultType 指明查询返回的结果集类型 --> <insert id="insertUser" useGeneratedKeys="true" keyProperty="id"> insert into user (username,password,sex,address) values (#{username},#{password},#{sex},#{address}) </insert> <update id="updateUser" parameterType="User"> update user set address=#{address} where id=#{id} </update> <delete id="deleteUser" parameterType="int"> delete from user where id=#{id} </delete> <!-- 如未为 Java Bean 起类别名,resultType="com.shiyanlou.mybatis.model.User" --> <!-- 使用resultType时,一定要保证,你属性名与字段名相同;如果不相同,就使用resultMap --> <select id="selectUserById" parameterType="int" resultType="User"> select * from user where id=#{id} </select> <select id="selectAllUser" resultMap="userMap"> select * from user </select> </mapper>
在 mybatis.cfg.xml 中加载它,在 mybatis.cfg.xml 中添加代码:
<mappers> <!-- 通过 mapper 接口包加载整个包的映射文件 --> <package name="com/zoey/mybatis/mapper" /> </mappers>
同时为Java Bean 起别名,添加如下代码:
<typeAliases> <!-- 指定一个包名起别名,将包内的 Java 类的类名作为类的类别名 --> <package name="com.zoey.mybatis.model" /> </typeAliases>
4.创建测试类
package com.zoey.mybatis.test; import java.io.IOException; import java.io.InputStream; 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; import com.zoey.mybatis.mapper.UserMapper; import com.zoey.mybatis.model.User; public class UserTest { private static SqlSessionFactory sqlSessionFactory; public static void main(String[] args) { String resource = "mybatis.cfg.xml"; //得到配置文件流 InputStream inputStream = null; try{ inputStream = Resources.getResourceAsStream(resource); }catch(IOException ie){ ie.printStackTrace(); } // 创建会话工厂,传入 MyBatis 的配置文件信息 sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); insertUser(); // updateUser(); // deleteUser(); // selectUserById(); //selectAllUser(); } // 新增用戶 private static void insertUser() { // 通过工厂得到 SqlSession SqlSession session = sqlSessionFactory.openSession(); UserMapper mapper = session.getMapper(UserMapper.class); User user = new User(); user.setUsername("Tom"); user.setPassword("123456"); user.setSex("male"); user.setAddress("chengdu"); try { mapper.insertUser(user); session.commit(); } catch (Exception e) { e.printStackTrace(); session.rollback(); } // 释放资源 session.close(); } // 更新用戶 private static void updateUser() { SqlSession session = sqlSessionFactory.openSession(); UserMapper mapper = session.getMapper(UserMapper.class); User user = null; try { user = mapper.selectUserById(1); } catch (Exception e1) { e1.printStackTrace(); } user.setAddress("chongqing"); try { mapper.updateUser(user); session.commit(); } catch (Exception e) { e.printStackTrace(); session.rollback(); } session.close(); } // 删除用戶 private static void deleteUser() { SqlSession session = sqlSessionFactory.openSession(); UserMapper mapper = session.getMapper(UserMapper.class); try { mapper.deleteUser(3); session.commit(); } catch (Exception e) { e.printStackTrace(); session.rollback(); } session.close(); } // 根据id查询用户信息 private static void selectUserById() { SqlSession session = sqlSessionFactory.openSession(); UserMapper mapper = session.getMapper(UserMapper.class); try { User user = mapper.selectUserById(1); session.commit(); System.out.println(user.getId() + " " + user.getUsername() + " " + user.getPassword() + " " + user.getSex() + " " + user.getAddress()); } catch (Exception e) { e.printStackTrace(); session.rollback(); } session.close(); } // 查询所有的用户信息 private static void selectAllUser() { SqlSession session = sqlSessionFactory.openSession(); UserMapper mapper = session.getMapper(UserMapper.class); try { List<User> userList = mapper.selectAllUser(); session.commit(); for (User user : userList) { System.out.println(user.getId() + " " + user.getUsername() + " " + user.getPassword() + " " + user.getSex() + " " + user.getAddress()); } } catch (Exception e) { e.printStackTrace(); session.rollback(); } session.close(); } }