原始Dao的开发方式:

1、创建数据库配置文件db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/数据库名称
jdbc.name=数据库登录用户名
jdbc.pwd=数据库登录密码

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>
<!--
加载属性文件
resource:属性文件的相对路径
url:属性文件的绝对路径
-->
<properties resource="config/db.properties">
<!--
配置一些属性
name:属性的名称
value:属性的值
-->
<!--<property name="" value="" /> -->
</properties>
<!--
环境配置
在和Spring整合后改配置将废除
-->
<environments default="development"> <environment id="development">
<!--使用JDBC的事务管理,事务管理交给Mybatis-->
<transactionManager type="JDBC"></transactionManager>
<!--数据库连接池,有Mybatis管理-->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.name}" />
<property name="password" value="${jdbc.pwd}" />
</dataSource>
</environment>
</environments>
</configuration>

3、创建PO类

public class User {
private int id;
private String username;
private Date birthday;
private String sex;
private String address; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public Date getBirthday() {
return birthday;
} public void setBirthday(Date birthday) {
this.birthday = birthday;
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
} public String getAddress() {
return address;
} public void setAddress(String address) {
this.address = address;
} @Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}

4、创建映射文件

<?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:命名空间,对SQL进行分类化的管理,进行sql隔离
-->
<mapper namespace="test">
<!--
查询sql语句配置使用select标签
id:该语句的唯一标识,通常称为statement的id
parameterType:输入参数的类型
resultType:返回数据的类型,指定为Java的po类型,则将查询出来的单条记录映射为po对象。
-->
<select id="findUserById" parameterType="int" resultType="com.jack.po.User" >
<!--
要执行的sql语句
#{} :表示一个占位符
#{value} :value表示接受的参数,名称为value,如果参数是简单类型,则名称可以随意起。
-->
SELECT * FROM user WHERE id=#{value}
</select> <select id="findUserByName" parameterType="String" resultType="com.jack.po.User">
SELECT * FROM user WHERE username LIKE '%${value}%'
</select> <insert id="insertUserInfo" parameterType="com.jack.po.User">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO user(username,birthday,sex,address) VALUE (#{username},#{birthday},#{sex},#{address})
</insert> <update id="updateUserInfo" parameterType="com.jack.po.User" >
UPDATE user set birthday=#{birthday},sex=#{sex},address=#{address} WHERE id=#{id}
</update> <update id="deleteUserInfo" parameterType="int" >
DELETE FROM user WHERE id=#{value}
</update>
</mapper>

5、在SqlMapConfig.xml中引入该映射文件

  <!--引入mapper-->
<mappers>
<mapper resource="config/sqlmap/userMapper.xml" />
</mappers>

6、编写Dao接口文件

public interface UserServiceI{

    //根据id查询用户的接口
public User findUserById(int id) throws Exception;
//根据用户名查询用户
public List<User> findUserByName(String name) throws Exception;
//插入用户信息
public int insertUserInfo(User user) throws Exception;
//根据id更新用户信息
public void updateUserInfo(User user) throws Exception;
//根据id删除用户信息
public void deleteUserInfo(int id) throws Exception;
}

7、编写接口实现类

public class UserServiceImpl  implements UserServiceI{

    private SqlSessionFactory sessionFactory;

    public UserServiceImpl(SqlSessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
}
@Override
public User findUserById(int id) throws Exception {
SqlSession session = sessionFactory.openSession();
User user = session.selectOne("findUserById",id);
return user;
} @Override
public List<User> findUserByName(String name) throws Exception {
SqlSession session = sessionFactory.openSession();
List<User> list = session.selectList("findUserByName",name);
return list;
} @Override
public int insertUserInfo(User user) throws Exception {
SqlSession session = sessionFactory.openSession();
session.insert("insertUserInfo",user);
session.commit();
return user.getId(); } @Override
public void updateUserInfo(User user) throws Exception {
SqlSession session = sessionFactory.openSession();
session.insert("updateUserInfo",user);
session.commit();
} @Override
public void deleteUserInfo(int id) throws Exception {
SqlSession session = sessionFactory.openSession();
session.delete("deleteUserInfo",id);
session.commit();
}
}

8、编写测试代码进行测试

public class UserTest {

    private SqlSessionFactory sessionFactory;
@Before
public void setUp() throws Exception{
String resource = "config/SqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource);
sessionFactory = new SqlSessionFactoryBuilder().build(in);
} @Test
public void findUserById(){
UserServiceI userService = new UserServiceImpl(sessionFactory);
try {
User user = userService.findUserById(10);
System.out.println(user);
} catch (Exception e) {
e.printStackTrace();
}finally { }
} @Test
public void findUserByName(){
UserServiceI userService = new UserServiceImpl(sessionFactory);
try {
List<User> list = userService.findUserByName("小明");
for (User user:list) {
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
}finally { }
} @Test
public void insertUserInfo(){
UserServiceI userService = new UserServiceImpl(sessionFactory);
try {
User user = new User();
user.setId(26);
user.setBirthday(new Date());
user.setSex("1");
user.setAddress("甘肃天水");
userService.updateUserInfo(user);
} catch (Exception e) {
e.printStackTrace();
}finally { }
} public void updateUserInfo(){
UserServiceI userService = new UserServiceImpl(sessionFactory);
try {
User user = new User();
user.setUsername("东方不败");
user.setBirthday(new Date());
user.setSex("0");
user.setAddress("黑木崖");
int id =userService.insertUserInfo(user);
System.out.println(id);
} catch (Exception e) {
e.printStackTrace();
}finally { }
} @Test
public void deleteUserInfo(){
UserServiceI userService = new UserServiceImpl(sessionFactory);
try {
userService.deleteUserInfo(28);
} catch (Exception e) {
e.printStackTrace();
}finally { }
}
}

Mybatis Dao开发的两种方式(一)的更多相关文章

  1. MyBatis开发Dao层的两种方式(原始Dao层开发)

    本文将介绍使用框架mybatis开发原始Dao层来对一个对数据库进行增删改查的案例. Mapper动态代理开发Dao层请阅读我的下一篇博客:MyBatis开发Dao层的两种方式(Mapper动态代理方 ...

  2. MyBatis开发Dao层的两种方式(Mapper动态代理方式)

    MyBatis开发原始Dao层请阅读我的上一篇博客:MyBatis开发Dao层的两种方式(原始Dao层开发) 接上一篇博客继续介绍MyBatis开发Dao层的第二种方式:Mapper动态代理方式 Ma ...

  3. MyBatis配置数据源的两种方式

    ---------------------siwuxie095                                     MyBatis 配置数据源的两种方式         1.配置方 ...

  4. MyBatis获取参数值的两种方式

    MyBatis获取参数值的两种方式:${}和#{} ${}的本质就是字符串拼接,#{}的本质就是占位符赋值 ${}使用字符串拼接的方式拼接sql,若为字符串类型或日期类型的字段进行赋值时,需要手动加单 ...

  5. mybatis批量保存的两种方式(高效插入)

    知识点:mybatis中,批量保存的两种方式 1.使用mybatis foreach标签 2.mybatis ExecutorType.BATCH 参考博客:https://www.jb51.net/ ...

  6. 数据库链接 mybatis spring data jpa 两种方式

    jdbc mybatis                     spring data jpa dao service webservice jaxrs     jaxws  springmvc w ...

  7. mybatis调用存储过程的两种方式

    先总结和说明一下注意点: 1.如果传入的某个参数可能为空,必须指定jdbcType 2.当传入map作为参数时,必须指定JavaType 3.如果做动态查询(参数为表名,sql关键词),可以使用${} ...

  8. mybatis 传递参数的两种方式与模糊匹配 很重要

  9. 在springboot中使用Mybatis Generator的两种方式

    介绍 Mybatis Generator(MBG)是Mybatis的一个代码生成工具.MBG解决了对数据库操作有最大影响的一些CRUD操作,很大程度上提升开发效率.如果需要联合查询仍然需要手写sql. ...

随机推荐

  1. mysql数据库使用sql查询数据库大小及表大小

    网上查了很多资料,最后发现一个可行的,分享如下: 数据库大小查询: select concat(round(sum(DATA_LENGTH/1024/1024),2),'M') from inform ...

  2. [LeetCode 题解]: Flatten Binary Tree to Linked List

    Given a binary tree, flatten it to a linked list in-place. For example,Given 1 / \ 2 5 / \ \ 3 4 6 T ...

  3. 7z文件格式及其源码的分析(五)

    这是7z文件格式及其源码的分析系列的第五篇. 上一篇讲到了7z文件压缩流程.最近太忙了,好久没更新,都快忘了写到哪了.:) 这一篇就说说7z文件的尾头的生成方式吧. 上一篇已经讲了尾header的结构 ...

  4. 把windows电脑变成路由器使用

    实用小技巧1 把windows电脑变成路由器使用 适用对象: windows7.windows8的笔记本电脑或者有无线网卡的台式电脑 网络要求: CMCC-EDU和家里拨号上网的都可以,但是电信的校园 ...

  5. ansible 常用模块的使用

    安装 yum -y install ansible 配置文件/etc/ansible/hosts 模块介绍与使用 ping模块 [root@node1 config]# ansible k8s -m ...

  6. 清北学堂(2019 4 30 ) part 3

    今天总的讲些算法,会了的话...看上去好厉害的样子: 1.老朋友动态规划DP: DP重点: 1.边界条件,开头不需处理的数据,比如斐波那契数列中的第一二项 2.转移方程,后面的项需要根据前面几项求出自 ...

  7. OCP 12c最新考试原题及答案(071-5)

    5.(4-12) choose two: You executed the following CREATE TABLE statement that resulted in an error: SQ ...

  8. KVM 安装 VMware 虚拟机

    去掉了“双引号”改为:vmx.allowNested = TRUE 打开在其中创建虚拟机的文件夹VMDISK和搜索与您的虚拟机的名称. vmx 文件. 用记事本打开它,并添加上述条目. 所以 vmx. ...

  9. React-Native 工程添加推送功能 (iOS 篇)

    推送已经是是手机应用的基本功能,如果自己实现一套推送系统费时费力,所有一般我们会使用第三方的推送服务,这里我使用「极光推送」作为集成推送的例子,因为有现成的 react native 插件 jpush ...

  10. String 源码浅析(一)

    前言 相信作为 JAVAER,平时编码时使用最多的必然是 String 字符串,而相信应该存在不少人对于 String 的 api 很熟悉了,但没有看过其源码实现,其实我个人觉得对于 api 的使用, ...