通过ID查询一个用户的两种开发方法

通过ID查询一个用户的两种开发方法

数据库建表sql语句如下:https://github.com/beyondyanyu/Sayingyy/blob/master/JDBC2-数据库sql建表语句

①,原始Dao开发:

UserDao.java(接口):

package com.pdsu.mybatis.dao;import com.pdsu.mybatis.pojo.User;public interface UserDao {//通过用户ID查询一个用户public User selectUserById(Integer id);}

UserDaoImpl.java(实现接口):

package com.pdsu.mybatis.dao;import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;import com.pdsu.mybatis.pojo.User;/*** * */
public class UserDaoImpl implements UserDao {//注入SQLSession工厂private SqlSessionFactory sqlsessionFactory;//构造器public UserDaoImpl(SqlSessionFactory sqlsessionFactory) {this.sqlsessionFactory = sqlsessionFactory;}//通过用户ID查询一个用户public User selectUserById(Integer id){SqlSession sqlSession = sqlsessionFactory.openSession(); return sqlSession.selectOne("user.findUserById", id);}
}

MybatisDaoTest.java测试

package com.pdsu.mybatis.junit;import java.io.InputStream;import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;import com.pdsu.mybatis.dao.UserDao;
import com.pdsu.mybatis.dao.UserDaoImpl;
import com.pdsu.mybatis.pojo.User;public class MybatisDaoTest {public SqlSessionFactory sqlSessionFactory;@Beforepublic void before() throws Exception{ //加载核心配置文件,加载要使用IO流进行读取String resource = "sqlMapConfig.xml";InputStream in = Resources.getResourceAsStream(resource);//创建SqlSessionFactorysqlSessionFactory = new SqlSessionFactoryBuilder().build(in);}@Testpublic void testDao() throws Exception{UserDao userDao = new UserDaoImpl(sqlSessionFactory);User user = userDao.selectUserById(10);System.out.println(user);//输出结果就是数据库中ID为10的用户信息}
}

User.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">
<!-- namespace:命名空间,用于隔离sql,还有一个很重要的作用,后面会讲 -->
<!-- 
命名空间:user.findUserById
命名空间:order.findUserById 
--><mapper namespace="com.pdsu.mybatis.mapper.UserMapper"><!-- resultType:返回值parameterType:输入参数 --><!-- 通过ID查询一个用户 --><select id="findUserById" parameterType="Integer" resultType="com.pdsu.mybatis.pojo.User">select * from user where id= #{sq}</select><!-- #{} === select * from user where username=     表示占位符?   sq可以随意替代=== select * from user where username= '思琪'${} === select * from user where username like '%${value}%'  表示字符串拼接  value不可以随意替代=== select * from user where username like '%琪%' 			sql 模糊语句查询=== select * from user where username like "%"'琪%'"%" 		sql 模糊语句查询=== select * from user where username like "%"#{sq}"%" --><!-- 根据用户名称模糊查询用户列表 --><select id="findUserByUsername" parameterType="String" resultType="com.pdsu.mybatis.pojo.User">select * from user where username like '%${value}%'</select><!-- 添加用户 --><insert id="insertUser" parameterType="com.pdsu.mybatis.pojo.User"><selectKey keyProperty="id" resultType="Integer" order="AFTER" >select LAST_INSERT_ID()</selectKey>insert into user(username,birthday,address,sex) values (#{username},#{birthday},#{address},#{sex})</insert><!-- 更新用户 --><update id="updateUserById" parameterType="com.pdsu.mybatis.pojo.User">update user set username = #{username},sex = #{sex},birthday = #{birthday},address = #{address}where id = #{id}</update>	<!-- 删除用户 --><delete id="deleteUserById" parameterType="Integer" >delete from user where id = #{sq}</delete></mapper>
②,Mapper动态代理开发:

UserMapper.java:

package com.pdsu.mybatis.mapper;import java.util.List;import com.pdsu.mybatis.pojo.User;public interface UserMapper {/*遵循四个原则对于:public User findUserById(Integer id);接口   方法名 == User.xml中id名 === findUserById返回值类型 与 Mapper.xml文件中返回值类型(resultType)要一致 === User === com.pdsu.mybatis.pojo.User方法的入参类型 与 Mapper.xml中入参类型(parameterType)要一致 === Integer id命名空间绑定此接口<mapper namespace="com.pdsu.mybatis.mapper.UserMapper">,User.xml中的路径为该接口全路径*/public User findUserById(Integer id);}

MybatisMapperTest.java:

package com.pdsu.mybatis.mapper;import static org.junit.Assert.*;import java.io.InputStream;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.pdsu.mybatis.pojo.User;public class MybatisMapperTest {@Testpublic void testMapper() throws Exception {//加载核心配置文件,加载要使用IO流进行读取String resource = "sqlMapConfig.xml";InputStream in = Resources.getResourceAsStream(resource);//创建SqlSessionFactorySqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);//SqlSessionFactoryBuilder这是一个实现类需要new一下//创建SQLSessionSqlSession sqlSession = sqlSessionFactory.openSession();	//SqlSession自动生成实现类(接口需要遵循四大原则)=== UserMapper.class为遵循四大原则的接口UserMapper userMapper = sqlSession.getMapper(UserMapper.class);User user = userMapper.findUserById(30);System.out.println(user);//输出结果就是数据库中id为30的用户信息}
}

User.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">
<!-- namespace:命名空间,用于隔离sql,还有一个很重要的作用,后面会讲 -->
<!-- 
命名空间:user.findUserById
命名空间:order.findUserById 
--><mapper namespace="com.pdsu.mybatis.mapper.UserMapper"><!-- resultType:返回值parameterType:输入参数 --><!-- 通过ID查询一个用户 --><select id="findUserById" parameterType="Integer" resultType="com.pdsu.mybatis.pojo.User">select * from user where id= #{sq}</select><!-- #{} === select * from user where username=     表示占位符?   sq可以随意替代=== select * from user where username= '思琪'${} === select * from user where username like '%${value}%'  表示字符串拼接  value不可以随意替代=== select * from user where username like '%琪%' 			sql 模糊语句查询=== select * from user where username like "%"'琪%'"%" 		sql 模糊语句查询=== select * from user where username like "%"#{sq}"%" --><!-- 根据用户名称模糊查询用户列表 --><select id="findUserByUsername" parameterType="String" resultType="com.pdsu.mybatis.pojo.User">select * from user where username like '%${value}%'</select><!-- 添加用户 --><insert id="insertUser" parameterType="com.pdsu.mybatis.pojo.User"><selectKey keyProperty="id" resultType="Integer" order="AFTER" >select LAST_INSERT_ID()</selectKey>insert into user(username,birthday,address,sex) values (#{username},#{birthday},#{address},#{sex})</insert><!-- 更新用户 --><update id="updateUserById" parameterType="com.pdsu.mybatis.pojo.User">update user set username = #{username},sex = #{sex},birthday = #{birthday},address = #{address}where id = #{id}</update>	<!-- 删除用户 --><delete id="deleteUserById" parameterType="Integer" >delete from user where id = #{sq}</delete></mapper>

小结(转载:黑马程序员):

selectOne和selectList
动态代理对象调用sqlSession.selectOne()和sqlSession.selectList()是根据mapper接口方法的返回值决定,如果返回list则调用selectList方法,如果返回单个对象则调用selectOne方法。

namespace
mybatis官方推荐使用mapper代理方法开发mapper接口,程序员不用编写mapper接口实现类,使用mapper代理方法时,输入参数可以使用pojo包装对象或map对象,保证dao的通用性。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/379443.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

duration java_Java Duration类| minusMinutes()方法与示例

duration java持续时间类minusMinutes()方法 (Duration Class minusMinutes() method) minusMinutes() method is available in java.time package. minusMinutes()方法在java.time包中可用。 minusMinutes() method is used to subtract the given duration in minutes from t…

Silverlight + WCF异步调用 例子

看大家好像对我的NParsing框架不是很感兴趣&#xff08;写NParsing帖没人顶我&#xff09;&#xff0c;那就给大家来点“甜品”&#xff0c;换换口谓。来说说Silverlight方面的东西。 在Silverlight中数据通信只能用异步。有人会觉得写起来很麻烦&#xff0c;其实不然。也有很简…

我博客主页的搜索功能怎么不好用

用博客里面的搜索功能&#xff0c;“找找看”&#xff0c;搜索我博客里面的关键字&#xff0c;但是不能出现结果。但是我在别人的主页上能够搜索该人的内容&#xff0c;能够查询到记录&#xff0c;难道博客园对每个博客的信息要先排序&#xff1f;目前我的还不在他的搜索数据库…

小议SqlMapConfig.xml配置文件

①、mybatis-3-config.dtd 主要用于mybatis的核心配文件sqlMapConfig.xml的约束 sqlMapConfig.xml代码如下&#xff1a; <?xml version"1.0" encoding"UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN&q…

ffmepg 命令提取音视频数据

原文件&#xff1a; 1&#xff1a; 原音频数据提取&#xff08;保留还是mp4的封装格式的&#xff09;&#xff1a; ffmpeg -i test_1920x1080.mp4 -acodec copy -vn audio.mp4 -vn 就是没有视频&#xff0c; -acodec copy 音频拷贝不进行任何转码 原视频数据提取&#xff0…

Java BigInteger类| modInverse()方法与示例

BigInteger类modInverse()方法 (BigInteger Class modInverse() method) modInverse() method is available in java.math package. modInverse()方法在java.math包中可用。 modInverse() method is used to calculate the mod inverse by using the inverse of (this BigInteg…

【7】jQuery学习——入门jQuery选择器之过滤选择器-可见性过滤选择器

这篇什么都不说&#xff0c;看标题就知道了&#xff0c;很简单&#xff0c;就2个选择器&#xff0c;嘿嘿 选择器描述返回$("Element:hidden")选取所有不可见的元素集合元素$("Element:visible")选取所有可见元素集合元素这篇很简单吧&#xff0c;就2个&…

Creating an undraggable TitleWindow container in Flex (转载)

The following examples show how you can create an undraggable TitleWindow container by setting the isPopUp property to false on the TitleWindow instance. <?xml version"1.0" encoding"utf-8"?><!-- http://blog.flexexamples.com/2…

汇编语言-003(LAHF_SAHF 、XCHG、FLAGS、 OFFSET、ALIGN、PTR、LENGTHOF、SIZEOF)

1&#xff1a;LAHF将EFLAGS符号寄存器低8位字节复制到AH&#xff0c;SAHF将AH复制到EFLAGS符号寄存器低8位字节 .386 .model flat,stdcall.stack 4096 ExitProcess PROTO,dwExitCode:DWORD.data saveflags BYTE ?.code main PROClahfmov saveflags ,ahmov ah,saveflagssahfIN…

Mybatis中的核心配置文件SqlMapConfig.xml详细介绍

一、properties&#xff08;属性&#xff09; 可以引用java属性文件中的配置信息如下 jdbc.properties代码如下&#xff1a; jdbc.drivercom.mysql.jdbc.Driver jdbc.urljdbc:mysql://localhost:3306/mybatis?characterEncodingutf-8 jdbc.usernameroot jdbc.passwordbeyond…

用Kotlin开发您的第一个应用程序| Android与Kotlin

In the previous article, we learned how to setup Kotlin in the android studio? Now moving to journey ahead we are going to develop our first app with Kotlin. It is the basic app, but it will let you know the structure of the program. 在上一篇文章中&#x…

数据结构与算法分析-第一章Java类(02)

编写一个名为Person的类&#xff0c;它包含分别表示人的名字与年龄的两个数据域。要求此类包含对其中任何一个数据域进行设置与获取的方法。还要求包含可进行下列测试的方法&#xff1a; 两个Person对象是否相等--即是否有相同的名称与年龄一个人是否比另一个人年长 最后&#…

asp.net对于长篇文章进行分页

对于文章篇幅比较长的&#xff0c;就必须采用分页显示。在.net中对长篇文章分页一般有2种方法&#xff0c;第一种就是先计算好一页的文字长度是多少&#xff0c;然后把文章总的长度除设置好的单页文字长度及可&#xff0c;用这方法可以减少认为进行分页的繁琐&#xff0c;但是这…

汇编语言-004(LABEL 、间接寻址、变址操作数、指针使用、TypeDef、LOOP、DWORD变量交换高位低位字)

1&#xff1a; LABEL : 为一个标号定义大小属性&#xff0c;但不分配内存与下一个变量共用内存&#xff0c;与C中UNION类似 .386 .model flat,stdcall.stack 4096 ExitProcess PROTO,dwExitCoed:DWORD.data val16 LABEL WORD val32 DWORD 12345678hLongValue LABEL DWORD val1…

(只需挨个复制粘贴命令即可部署)在Centos7下搭建文件服务器(VSFTPD)

观看北京尚学堂-百战程序员笔记一、VSFTPD简介 Linux的组件&#xff08;一款软件&#xff09;&#xff0c;安装到Linux后可以通过java代码&#xff08;FtpClient&#xff09;实现文件的上传。基于FTP协议。 由于VSFTPD是基于FTP协议&#xff0c;客户端浏览器是需要通过http协议…

POJ 2421 Constructing Roads MST kruskal

最近刚学的并查集所以用kruskal来试试最小生成树~ kruskal其实用几句话就能说完~ 1.贪心所有边的权值,从小到大取值 2.取值时~将边权非0的两个顶点~进行并查操作~如果两个点的祖先不同...边权加入最小生成树...并且将两个点纳入同一个集合中 3.判断是否所有点都在同一个集合中…

c# 声明类的时候初始化类_使用C#初始化的列表声明

c# 声明类的时候初始化类The task is to create/declare a list with an initializer list in C#. 任务是在C&#xff03;中使用初始化列表创建/声明一个列表 。 C&#xff03;清单 (C# List) A list is used to represent the list of the objects, it is represented as Lis…

编写程序计算所输日期是当年的第几天

/* 1.输入年月日&#xff0c;编写程序计算所输日期是当年的第几天 *//* 2.已知列车隔日发车&#xff0c;且1/1/2006不发车(无ticket),如果所输入数据在此日期之后&#xff0c;则输出有没有车票&#xff0c;否则仅输出上一步结果。*/ /* month/date/year is which day of the ye…

汇编语言-005(XCHG、标志位操作、算术操作、比例因子的变址寻址、多个常用运算符运用、大端转小端、数组操作)

1: 用不超过3条XCHG指令对4个8位寄存器的值重新排序&#xff0c;A,B,C,D调整为D,C,B,A .386 .model flat,stdcall.stack 4096 ExitProcess PROTO,dwExitCode:DWORD.data.code main PROCmov al,Amov bl,Bmov cl,Cmov dl,Dxchg al,dlxchg bl,clINVOKE ExitProcess,0 main ENDP E…

bcd码二进制转十进制_二进制编码的十进制(BCD码)及其加法

bcd码二进制转十进制Prerequisite: Number systems 先决条件&#xff1a; 数字系统 BCD Code (8421 Code): In BCD 8421 code, each decimal digit is represented using a 4-bit binary number. The 4-bit binary numbers have their weights attached as 8, 4, 2, 1 from MS…