mybatis 資料庫語句
阿新 • • 發佈:2020-10-08
mybatis 操作資料庫增刪改查
package com.school.mybatis.junit; 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 org.junit.Test; import com.school.mybatis.pojo.sysUser; public class mybatisTest { @Test public void testmybatis() throws Exception{ //載入核心配置檔案 String resource = "sqlMapConfig.xml"; InputStream in = Resources.getResourceAsStream(resource); //建立SqlSessionFactorySqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); SqlSession sqlSessino = sqlSessionFactory.openSession(); //執行sql語句 //通過ID查詢 sysUser user1 = sqlSessino.selectOne("test.findUserById", 1); System.out.println(user1); //模糊查詢List<sysUser> user2 = sqlSessino.selectList("test.findUserByUsername", "l"); for (sysUser user3 : user2) { System.out.println(user3); } //新增使用者 sysUser suser = new sysUser(); suser.setSysUserName("lhj"); suser.setPassWord("123456"); sqlSessino.insert("test.insersysUser",suser); sqlSessino.commit(); } @Test public void testUpdateById() throws Exception{ //載入核心配置檔案 String resource = "sqlMapConfig.xml"; InputStream in = Resources.getResourceAsStream(resource); //建立SqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); SqlSession sqlSessino = sqlSessionFactory.openSession(); //修改使用者 sysUser sysuser = new sysUser(); sysuser.setId(1); sysuser.setSysUserName("lhj29"); sysuser.setPassWord("123456"); sqlSessino.update("test.UpdateUserById", sysuser); sqlSessino.commit(); //刪除使用者 sqlSessino.delete("test.deleteUserById", 1); sqlSessino.commit(); } }
操作資料庫
<?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"> <!-- 寫sql語句 --> <!-- namespace為名稱空間 --> <mapper namespace="test"> <!-- 通過ID查詢一個使用者 --> <select id="findUserById" parameterType="Integer" resultType="com.school.mybatis.pojo.sysUser"> select * from sysUser where id = #{v} </select> <select id="findUserByUsername" parameterType="String" resultType="com.school.mybatis.pojo.sysUser"> select * from sysuser where sysUsername like '%${value}%' </select> <!-- #{} 佔位符 ${} 字串拼接 如: select * from sysuser where sysUsername like '%${}%' ${}等於連線字串的 ‘+’ --> <insert id="insersysUser" parameterType="com.school.mybatis.pojo.sysUser"> insert into sysUser (sysUsername,password) values (#{SysUserName},#{PassWord}) </insert> <update id="UpdateUserById" parameterType="com.school.mybatis.pojo.sysUser"> update sysUser set SysUserName=#{SysUserName},PassWord=#{PassWord} where id = #{Id} </update> <delete id="deleteUserById" parameterType="Integer"> delete from sysUser where id = #{v} </delete> </mapper>