IDEA中使用MyBatis(基础)
项目骨架图
一:使用IDEA创业Maven项目并在pom.xml中导入使用mybatis的相关依赖
<dependencies>
<!--单元测试-->
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<!--数据库驱动-->
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<!--mybatis驱动 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency>
二:编写(mysql)数据库配置文件
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/数据库名称?useUniCode=true&characterEncoding=utf-8 jdbc.username=账号 jdbc.password=密码
三:编写mybatis-config.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>
<!--引入数据库配置文件--> <properties resource="jdbc.properties"></properties> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <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>
<!--导入跟接口对应的XML文件-->
<mappers> <mapper resource="com/yjc/dao/IUserDao.xml"/> </mappers> </configuration>
四:在接口中编写需要实现的方法(实体类在最后)
package com.yjc.dao; import com.yjc.entity.User; import java.util.List; public interface IUserDao { public int getByUser();//查询用户数量 public List<User> getUser(String name);//查询所有用户信息 public int insertUser(User user);//新增用户 public int updateUser(User user);//修改用户信息 public int deleteUser(Integer id);//删除用户 }
五:编写和接口相互映射的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.yjc.dao.IUserDao"> //namespace指向相应的接口地址 <select id="getByUser"> //id值与接口中的方法名相同 SELECT count(1) FROM smbms_user </select> <select id="getUser" resultType="com.yjc.entity.User"> SELECT * FROM smbms_user </select> <insert id="insertUser" parameterType="com.yjc.entity.User" > INSERT INTO smbms_user VALUES (DEFAULT,#{userCode},#{userName},#{userPassword},#{gender},#{birthday},#{phone},#{address},#{userRole},#{createdBy},#{creationDate},#{modifyBy},#{modifyDate}) </insert> <update id="updateUser" parameterType="com.yjc.entity.User" > UPDATE smbms_user SET userName=#{userName} WHERE id=#{id} </update> <delete id="deleteUser"> DELETE FROM smbms_user WHERE id=#{_parameter} </delete> </mapper>
parameterType为参数类型,基本数据类型可以省略,
resultType为返回值类型,增删改默认返回int类型数据(代表受影响的行数)
六:变成测试类进行数据测试
@Test public void testone(){ try {String resource="mybatis-config.xml"; InputStream is = Resources.getResourceAsStream(resource);//加载核心配置文件 SqlSessionFactory factory =new SqlSessionFactoryBuilder().build(is); //获得工厂对象 int count =0; SqlSession sqlSession=factory.openSession(); //获取核心对象 count =sqlSession.selectOne("getByUser"); List<User> user=sqlSession.selectList("getUser"); SimpleDateFormat simpleDateFormat=new SimpleDateFormat(); Date date=new Date(); User user1=new User("yangjinchuan","天雁","123456",2,date,"1361001001","五道口",2,1,date,1,date); sqlSession.insert("insertUser", user1); User user2=new User(); user2.setUserName("天雁"); user2.setId(1); int updateUser = sqlSession.update("updateUser", user2); sqlSession.commit(); System.out.println(updateUser);*/ sqlSession.delete("deleteUser",31); sqlSession.commit(); //修改数据库操作需要惊喜手动的事务提交(增删改) sqlSession.close(); //需要关闭sqlSession对象释放资源 } catch (Exception e) { e.printStackTrace(); } }
实体类
package com.yjc.entity; import java.util.Date; /** * smbms_user 实体类 * @author liangzz * @date2019-09-24 09:02 */ public class User { /**主键ID**/ private Integer id; /**用户编码**/ private String userCode; /**用户名称**/ private String userName; public User() { } public User(String userCode, String userName, String userPassword, Integer gender, Date birthday, String phone, String address, Integer userRole, Integer createdBy, Date creationDate, Integer modifyBy, Date modifyDate) { this.userCode = userCode; this.userName = userName; this.userPassword = userPassword; this.gender = gender; this.birthday = birthday; this.phone = phone; this.address = address; this.userRole = userRole; this.createdBy = createdBy; this.creationDate = creationDate; this.modifyBy = modifyBy; this.modifyDate = modifyDate; } /**用户密码**/ private String userPassword; /**性别(1:女、 2:男)**/ private Integer gender; /**出生日期**/ private Date birthday; /**手机**/ private String phone; /**地址**/ private String address; /**用户角色(取自角色表-角色id)**/ private Integer userRole; /**创建者(userId)**/ private Integer createdBy; /**创建时间**/ private Date creationDate; /**更新者(userId)**/ private Integer modifyBy; /**更新时间**/ private Date modifyDate; public void setId(Integer id){ this.id=id; } public Integer getId(){ return id; } public void setUserCode(String userCode){ this.userCode=userCode; } public String getUserCode(){ return userCode; } public void setUserName(String userName){ this.userName=userName; } public String getUserName(){ return userName; } public void setUserPassword(String userPassword){ this.userPassword=userPassword; } public String getUserPassword(){ return userPassword; } public void setGender(Integer gender){ this.gender=gender; } public Integer getGender(){ return gender; } public void setBirthday(Date birthday){ this.birthday=birthday; } public Date getBirthday(){ return birthday; } public void setPhone(String phone){ this.phone=phone; } public String getPhone(){ return phone; } public void setAddress(String address){ this.address=address; } public String getAddress(){ return address; } public void setUserRole(Integer userRole){ this.userRole=userRole; } public Integer getUserRole(){ return userRole; } public void setCreatedBy(Integer createdBy){ this.createdBy=createdBy; } public Integer getCreatedBy(){ return createdBy; } public void setCreationDate(Date creationDate){ this.creationDate=creationDate; } public Date getCreationDate(){ return creationDate; } public void setModifyBy(Integer modifyBy){ this.modifyBy=modifyBy; } public Integer getModifyBy(){ return modifyBy; } public void setModifyDate(Date modifyDate){ this.modifyDate=modifyDate; } public Date getModifyDate(){ return modifyDate; } @Override public String toString() { return "User{" + "id=" + id + ", userCode='" + userCode + '\'' + ", userName='" + userName + '\'' + ", userPassword='" + userPassword + '\'' + ", gender=" + gender + ", birthday=" + birthday + ", phone='" + phone + '\'' + ", address='" + address + '\'' + ", userRole=" + userRole + ", createdBy=" + createdBy + ", creationDate=" + creationDate + ", modifyBy=" + modifyBy + ", modifyDate=" + modifyDate + '}'; } }
初学MyBatis,如有不便,请多担待,MyBatis代码后续还可以进行简化
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)