阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

MyBatis持久层的传统开发

161次阅读
没有评论

共计 7598 个字符,预计需要花费 19 分钟才能阅读完成。

1、MyBatis 持久层的传统开发 - 上

1.1、创建项目

**GroupId:**com.tianyi

**ArtifactId:**mb004

**Version:**1.0-SNAPSHOT

1.2、修改 pom.xml 加入包

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tianyi</groupId> <artifactId>mb004</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.11</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> </project>

1.3、创建实体类(User.java)

package com.tianyi.javabean; import java.io.Serializable; import java.util.Date; public class User implements Serializable {private Integer id; private String username; private Date birthday; private String sex; private String address; public Integer getId() {return id; } public String getUsername() {return username; } public Date getBirthday() {return birthday; } public String getSex() {return sex; } public String getAddress() {return address; } public void setId(Integer id) {this.id = id; } public void setUsername(String username) {this.username = username; } public void setBirthday(Date birthday) {this.birthday = birthday; } public void setSex(String sex) {this.sex = sex; } 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.4、创建持久层接口(IUserDao.java)

package com.tianyi.dao; import com.tianyi.javabean.User; import java.util.List; public interface IUserDao {List<User> findAll(); User findById(Integer id); int addUser(User u); int updateUser(User u); int deleteUser(Integer id); int allCount(); List<User> findByName(String username); }

1.5、创建持久层实现类(UserDaoImpl.java)

package com.tianyi.dao.impl; import com.tianyi.dao.IUserDao; import com.tianyi.javabean.User; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import java.util.List; public class UserDaoImpl implements IUserDao {private SqlSessionFactory factory; public UserDaoImpl(SqlSessionFactory factory) {this.factory = factory; } public List<User> findAll() {SqlSession session = factory.openSession(); List<User> users = session.selectList("com.tianyi.dao.IUserDao.findAll"); session.close(); return users; } public User findById(Integer id) {SqlSession session =factory.openSession(); User user = session.<User>selectOne("com.tianyi.dao.IUserDao.findById", id); session.close(); return user; } public int addUser(User u) {SqlSession session =factory.openSession(); int n=session.insert("com.tianyi.dao.IUserDao.addUser",u); session.commit(); session.close(); return n; } public int updateUser(User u) {SqlSession session =factory.openSession(); int n=session.update("com.tianyi.dao.IUserDao.updateUser",u); session.commit(); session.close(); return n; } public int deleteUser(Integer id) {SqlSession session =factory.openSession(); int n=session.delete("com.tianyi.dao.IUserDao.deleteUser",id); session.commit(); session.close(); return n; } public int allCount() {SqlSession session =factory.openSession(); int n=session.selectOne("com.tianyi.dao.IUserDao.allCount"); session.close(); return n; } public List<User> findByName(String username) {SqlSession session =factory.openSession(); List<User> users=session.selectList("com.tianyi.dao.IUserDao.findByName",username); session.close(); return users; } }

2、MyBatis 持久层的传统开发 - 中

2.1、持久层的映射配置(IUserDao.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="com.tianyi.dao.IUserDao"> <select id="findAll" resultType="com.tianyi.javabean.User"> select * from user </select> <select id="findById" resultType="com.tianyi.javabean.User" parameterType="int"> select * from user where id=#{id} </select> <insert id="addUser" parameterType="com.tianyi.javabean.User"> <selectKey keyColumn="id" keyProperty="id" resultType="java.lang.Integer"> select last_insert_id() </selectKey> insert into user (username,birthday,sex,address)values(#{username},#{birthday},#{sex},#{address}) </insert> <update id="updateUser" parameterType="com.tianyi.javabean.User"> update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id} </update> <delete id="deleteUser" parameterType="java.lang.Integer"> delete from user where id=#{id} </delete> <select id="allCount" resultType="java.lang.Integer"> select count(*) from user </select> <select id="findByName" parameterType="java.lang.String" resultType="com.tianyi.javabean.User" > select * from user where username like #{username} </select> </mapper>

2.2、创建 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> <!-- 配置 mybatis 的环境 --> <environments default="mysql"> <!-- 配置 mysql 的环境 --> <environment id="mysql"> <!-- 配置事务的类型 --> <transactionManager type="JDBC"></transactionManager> <!-- 配置连接数据库的信息: 用的是数据源 (连接池) --> <dataSource type="POOLED"> <!-- <property name="driver" value="com.mysql.jdbc.Driver"/>--> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mb"/> <property name="username" value="root"/> <property name="password" value="root1234"/> </dataSource> </environment> </environments> <!-- 告知 mybatis 映射配置的位置 --> <mappers> <mapper resource="com/tianyi/dao/IUserDao.xml"/> </mappers> </configuration>

3、MyBatis 持久层的传统开发 - 下

3.1、编写测试类(MbTest.java)

package com.tianyi.test; import com.tianyi.dao.IUserDao; import com.tianyi.dao.impl.UserDaoImpl; import com.tianyi.javabean.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; public class MbTest {private InputStream in ; private SqlSessionFactory factory; private IUserDao userDao; @Test public void findAll(){List<User> users = userDao.findAll(); for(User user : users) {System.out.println(user); } } @Test public void findById(){User user=userDao.findById(8); System.out.println(user.toString()); } @Test public void addUser(){User user=new User(); user.setUsername("李国"); user.setSex("男"); user.setAddress("北京昌平"); user.setBirthday(new Date()); int n=userDao.addUser(user); System.out.println(n+":"+user.getId()); } @Test public void updateUser(){User user=new User(); user.setId(10); user.setUsername("李国"); user.setSex("男"); user.setAddress("北京昌平"); user.setBirthday(new Date()); int n=userDao.updateUser(user); System.out.println(n+":"+user.getId()); } @Test public void deleteUser(){int n=userDao.deleteUser(19); System.out.println(n); } @Test public void allCount(){int n=userDao.allCount(); System.out.println(n); } @Test public void findByName(){List<User> users=userDao.findByName("王 %"); for(User user:users){System.out.println(user); } } @After// 在测试方法执行完成之后执行 public void destroy() throws Exception{in.close(); } @Before// 在测试方法执行之前执行 public void init()throws Exception {//1. 读取配置文件 in = Resources.getResourceAsStream("SqlMapConfig.xml"); //2. 创建构建者对象 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); //3. 创建 SqlSession 工厂对象 factory = builder.build(in); //4、初始化 userDao userDao=new UserDaoImpl(factory); } }

注意:

pom.xml

<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.9</maven.compiler.source> <maven.compiler.target>1.9</maven.compiler.target> </properties>

SqlMapConfig.xml

jdbc:mysql://192.168.1.123:3306/mybatis?serverTimezone=UTC

正文完
星哥玩云-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2022-06-06发表,共计7598字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中