1、环境搭建
1.1 表结构
create table user ( id int primary key auto_increment, username varchar(20) not null, birthday date, sex char(1) default '男', address varchar(50) ); insert into user values (null, '孙悟空','1980-10-24','男','花果山水帘洞'); insert into user values (null, '白骨精','1992-11-12','女','白虎岭白骨洞'); insert into user values (null, '猪八戒','1983-05-20','男','福临山云栈洞'); insert into user values (null, '蜘蛛精','1995-03-22','女','?丝洞');
1.2 创建项目
导入如下jar
- mybatis框架包
- 数据库驱动包
- log4j日志包
- junit单元测试包
1.3 准备配置文件
在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> <!--配置数据库连接参数--> <environments default="mybatis"> <environment id="mybatis"> <!--事务管理器--> <transactionManager type="JDBC"></transactionManager> <!--配置数据源--> <dataSource type="pooled"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///test"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> </configuration>
在 src 下准备配置文件:log4j.properties
# 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
2-增删改查源码
1.1 执行结果
1.2 User类代码
import java.sql.Date; /** 用户实体类对象 */ public class User { private Integer id; private String username; private Date birthday; private String sex; private String address; public User() { } public User(Integer id, String username, Date birthday, String sex, String address) { this.id = id; this.username = username; this.birthday = birthday; this.sex = sex; this.address = 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 Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } 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; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", birthday=" + birthday + ", sex='" + sex + '\'' + ", address='" + address + '\'' + '}'; } }
1.3 UserMapper接口代码
package com.vg.dao; import com.vg.entity.User; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 数据访问层接口:对用户进行增删改查操作 */ public interface UserMapper { /** * 添加用户 */ int addUser(User user); /** * 根据id删除用户 */ void deleteUser(Integer id); /** * 通过id修改用户信息 */ /** * 修改用户信息 */ void updateUser(User user); /** * 查询所有用户 */ List<User> findAllUsers(); /** * 根据id查询用户 */ User findUserById(int id); /** * 根据用户名模糊查询用户 */ List<User> findUsersByName(String username); /** * 根据姓名和性别查询用户数据(姓名使用模糊查询) */ /** * 根据用户名称模糊查询用户 */ } }
1.4 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属性的作用:关联接口,需要配置对应接口的类全名字符串 --> <mapper namespace="com.vg.dao.UserMapper"> <!-- 完成接口映射配置文件UserMapper.xml的编写:这个映射文件就相当于UserMapper接口实现类配置 --> <!--select标签的作用:用来配置查询要执行的SQL语句 id属性:关联接口中的方法名 resultType属性:设置方法返回的数据类型,如果是集合则配置集合元素的类型 --> <select id="findAllUsers" resultType="User"> select * from user </select> <select id="findUserById" parameterType="int" resultType="User"> select * from user where id = #{id}; </select> <select id="findUsersByName" parameterType="string" resultType="User"> select *from user where username like #{username} </select> <insert id="addUser" parameterType="user" > insert into user values(null,#{username},#{birthday},#{sex},#{address}); </insert> <update id="updateUser" parameterType="user"> update user set username = #{username}, birthday = #{birthday},sex = #{sex}, address = #{address} where id = #{id} </update> <delete id="deleteUser" parameterType="integer"> delete from user where id = #{id} </delete> </mapper>
1.5 在主配置文件中加载接口映射文件
<mappers> <!--mapper标签:一个该标签就配置一个接口映射文件 resource属性:配置映射文件的路径,路径分隔符使用 / : com/vg/dao/UserMapper.xml url:用于配置互联网上的映射文件的路径,比如:http://www.baidu.com/xxx.xml --> <!--<mapper resource="com/vg/dao/UserMapper.xml"></mapper>--> <package name="com.vg.dao"/> </mappers>
1.6 测试类代码
package com.vg.test; import com.vg.dao.UserMapper; import com.vg.entity.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.BeforeClass; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.sql.Date; import java.util.List; /** * 测试类 */ public class TestUserMapper { private static SqlSessionFactory sqlSessionFactory =null; private SqlSession sqlSession =null; private UserMapper userMapper =null; // 该方法在所有测试方法执行之前执行1次 @BeforeClass public static void init() throws Exception { // 1. 通过Resources类,加载sqlMapConfig.xml,得到文件输入流对 InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml"); // 2. 实例化会话工厂创建类SqlSessionFactoryBuilder对象 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); // 3. 根据字节输入流获取SqlSessionFactory对象 sqlSessionFactory = builder.build(in); } // 该方法会在每个测试方法执行之前执行1次 @Before public void before(){ // 4. 获取SqlSession对象,等价连接对象 // true:事务自动提交,false:不自动提交,默认值 sqlSession = sqlSessionFactory.openSession(); // 5. 创建接口 实现类对象 userMapper = sqlSession.getMapper(UserMapper.class); } /** * 测试方法:通过用户名模糊查询用户 */ @Test public void testAddUser() throws Exception{ // 1. 获得接口代理对象 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); // 2. 创建User对象 User u = new User(); u.setUsername("如来佛祖111"); u.setBirthday(Date.valueOf("1980-01-20")); u.setAddress("西天灵山"); u.setSex("男"); // 3. 保存用户信息 int row = userMapper.addUser(u); System.out.println("row = " + row); // 4. 手动提交事务 sqlSession.commit(); } /** * 测试方法:通过用户名模糊查询用户 */ @Test public void testFindUserByName() throws Exception{ List<User> userList = userMapper.findUsersByName("%精%"); for (User user : userList) { System.out.println(user); } } /** * 测试方法:查询所有用户 */ @Test public void testFindAllUsers() throws Exception{ List<User> userList = userMapper.findAllUsers(); for (User user : userList) { System.out.println(user); } } /** * 根据id查询用户 * @throws Exception */ @Test public void testFindUserById()throws Exception{ // 6. 调用接口的方法根据id查询用户 User user = userMapper.findUserById(1); System.out.println("user = " + user); } @Test public void testUpdateUser()throws Exception{ // 创建用户对象 User user = new User( 6, "牛魔王", Date.valueOf("1998-02-20"), "妖", "牛魔洞"); // 更新用户 userMapper.updateUser(user); // 提交事务 sqlSession.commit(); } @Test public void testDeleteUser()throws Exception{ // 1. 获得接口代理对象 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); // 2. 根据id删除用户 userMapper.deleteUser(6); // 3. 提交事务 sqlSession.commit(); } @After public void after() { // 7. 关闭会话,释放资源。 sqlSession.close(); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。
- 本文固定链接: https://www.zxbcw.cn/post/198730/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)