本文主要是介绍MyBatis的增删改查基本操作,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
MyBatis和Hibernate的使用基本一样,区别在于Hibernate在Java代码中实现数据库操作,集成度高;Mybatis在注解或者xml文件中通过配置实现SQL语句,更加灵活
创建使用MyBatis的Java项目
1. 创建并配置
- 创建Java项目并引入MyBaits的jar文件
- 配置log4j.properties(用于查看执行的SQL语句,日志等)
log4j.rootLogger=DEBUG,Consolelog4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d[%t]%-5p[%c]-%m%nlog4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
- 配置MyBaits的配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><environments default="development"><environment id="development"><transactionManager type="JDBC" /><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost/mybatis?useSSL=false" /><property name="username" value="root" /><property name="password" value="123456" /></dataSource></environment></environments><!-- 映射文件 --><mappers><mapper resource="map/query.xml" /><mapper resource="map/insert.xml" /><mapper resource="map/update.xml" /><mapper resource="map/delete.xml" /></mappers>
</configuration>
2.实现增删改查操作
- 创建和数据库表对应的JavaBean
- 创建相应的文件
- 通过Java中调用实现相关操作
//加载配置文件并初始化
public class InsertTest {public static void main(String[] args) {String resource = "map/mybatis.xml";Reader reader = null;SqlSessionFactory factory = null;SqlSession session = null;try {reader = Resources.getResourceAsReader(resource);factory = new SqlSessionFactoryBuilder().build(reader);session = factory.openSession();/***具体功能实现部分**/session.commit();} catch (IOException e) {session.rollback();e.printStackTrace();} finally {session.close();}}
}
- insert.xml
<!-- 插入新数据 --><!-- 语句的id,传入的数据类型,语句类型为预编译语句,主键是id,由数据库处理主键值 --><insert id="insert" parameterType="pojo.User" statementType="PREPARED"keyProperty="id" useGeneratedKeys="true">insert into mybatis(name,password)values(#{name},#{password})</insert>
- insert实现
User user = new User(1, "果粒橙", "果粒橙");session.insert("insert", user);
- delete.xml
<!-- 删除数据 --><delete id="deleteByObject" parameterType="pojo.User">delete from mybatiswhere id = #{id}</delete><delete id="deleteByID" parameterType="int">delete from mybatis whereid = #{id}</delete>
- delete实现
// 通过对象删除User user = new User();user.setId(3);session.delete("deleteByObject", user);// 通过ID删除session.delete("deleteByID", 2);
- update.xml
<!-- 更新数据 --><!-- id,插入的数据类型 --><update id="update" parameterType="pojo.User">update mybatis set name=#{name},password=#{password}where id = #{id}</update>
- update实现
User user = new User(3, "益达", "你的益达");session.update("update", user);
- query.xml
<!-- 根据ID查询一个结果,返回值类型为User对象 --><select id="queryUser" resultType="pojo.User">select * from mybatis where id = #{id}</select><!-- 查询多个结果,返回值类型为User对象 --><select id="queryUsers" resultType="pojo.User">select * from mybatis</select><!-- 查询多个结果,返回resultMap --><resultMap type="pojo.User" id="queryResultMap"><id column="id" property="id"></id><result property="name" column="name" /><result property="password" column="password" /></resultMap><select id="queryMap" resultMap="queryResultMap">select * from mybatis</select>
- query实现
// 返回一个查询结果,返回resultTypeUser user = session.selectOne("queryUser", 1);System.out.println(user.getName());// 返回多个查询结果,返回resultTypeList<User> results = session.selectList("queryUsers");for (User user1 : results) {System.out.println(user1.getName() + "---" + user1.getPassword());}// 返回多个结果,返回resultMapList<User> results1 = session.selectList("queryMap");for (User user2 : results1) {System.out.println(user2.getName() + "---" + user2.getPassword());}
- 表
项目下载
这篇关于MyBatis的增删改查基本操作的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!