springboot学习笔记(二)后端的数据库处理mybatis 新手向

springboot学习笔记(二)后端的数据库处理mybatis

后端的数据库处理mybatis

前言

本文表达不是很专业,希望尽可能通俗方便理解,主要有两个目的:
(1)记录开发过程的技术、方法、问题。
(2)供其他人参考。

1.entity包

上一篇日记已经提到了文件的结构,entity中是实体类和关系数据库中存储的对象对应,也叫pojo对象,对象可以不加注解。
在这里插入图片描述
随便放一个User类做例子:

package com.two.entity;
/**
 * Title: User
 * Description:用户pojo类,mybatis工具对应的实体类。
 * Version:1.0.0
 */
public class User1 {
    /**
     * 编号
     */
    private int user_id;
    /**
     * 姓名
     */
    private String user_name;
    /**
     * 电话号
     */
    private String phone;
    /**
     * 密码
     */
    private String password;
    /**
     * 用户的类型
     */
    private int type = 0;


    public int getUser_id() {
        return user_id;
    }

    public String getUser_name() {
        return user_name;
    }

    public String getPhone() {
        return phone;
    }

    public void setUser_id(int user_id) {
        this.user_id = user_id;
    }

    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setType(int type) {
        this.type = type;
    }
}

2.dao层

dao层即数据持久层,在你将mybatis的依赖加入以后,你可以给dao类增加 @Mapper注解,这样系统扫描时会将其标注,同时你要在mapper.xml文件中设置对应的namespace指向这个dao类,这样xml文件和dao类就关联了起来,在xml文件中可以设置方法对应的sql,这个在别的文章中写。
具体代码示例:
这里我的dao接口都继承了泛型接口(为了减少代码量,不用泛型也没有关系,可以直接写接口),在这个接口中只需要声明需要的方法,具体的实现是在mapper.xml文件中进行配置,不需要写Java代码,编辑xml文件即可,mybatis会自动的实现

package com.two.dao;

import java.util.List;

/**
 * @author lhn
 * 数据基础层
 */
public interface BaseDao<T> {
    //插入数据
    void insert(T entity);
    //批量增加数据
    int insertBatch(List<T> entityList) throws Exception;
    //更新数据
    void update(T entity) throws Exception;
    //根据ID删除数据
    void deleteByPrimaryKey(int id) throws Exception;
    //删除数据
    void delete(T entity) throws Exception;
    //根据id查询单个记录
    T findByPrimaryKey(int id);
    //根据用户名字查询单个记录
    T findByUsername(String username);
    //根据对象查询单个记录
    T findByEntity(T entity);
    //根据对象查询多条记录
    List<T> findByListEntity(T entity);
    //查询所有记录
    List<T> findAll();
    //根据对象查询信息
    Object findByObject(Object obj);
}
package com.two.dao;
import com.two.entity.User1;
import org.apache.ibatis.annotations.Mapper;
/**
 *
 * Title: UserDao
 * Description:
 * 用户数据接口
 * Version:1.0.0
 */
@Mapper
public interface UserDao2 extends BaseDao<User1>{
}

映射的mapper.xml文件:xml文件中的id对应dao中的方法名。

<?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.two.dao.UserDao2">
    <resultMap id="BaseResultMap" type="com.two.entity.User1">
        <result column="user_id" property="user_id" />
        <result column="user_name" property="user_name" />
        <result column="phone" property="phone" />
        <result column="password" property="password" />
    </resultMap>

    <parameterMap id="User1" type="com.two.entity.User1"/>

    <sql id="Base_Column_List">
		user_id, user_name, phone, password
	</sql>

    <insert id="insert" parameterMap="User1">
		insert into user (user_name,phone,password)
		values (#{user_name},#{phone},#{password})
	</insert>

    <update id="update" parameterMap="User1">
        update
        t_user
        set
        <if test="name!=null and name!=''">
            name = #{name}
        </if>

        <if test="age!=null and age!=''">
            , age = #{age}
        </if>
        where id= #{id}
    </update>

    <delete id="delete" parameterType="java.lang.Long">
		delete from  t_user where id=#{id}
	</delete>

    <select id="findAll" resultMap="BaseResultMap" >
		select
		*
		from user
	</select>

    <select id="findByPrimaryKey" resultMap="BaseResultMap" >
		select
		*
		from user where
		<if test="user_id!=null">
            user_id = #{user_id}
        </if>
	</select>

    <select id="findByUsername" resultMap="BaseResultMap">
        select
        *
        from user where
        <if test="user_name!=null">
            user_name = #{user_name}
        </if>
    </select>

</mapper>

将dao和xml完成后,dao层就完成了,这样就可以通过dao类进行查询。

3.service包

服务层:现在我只写了一些简单的查询,所以service的方法和dao的方法基本相同,增加了异常处理和日志记录,这样可以在出错时看到问题出在哪里,这里的示例代码涉及了四个类或者接口,可能看起来比较复杂,但是基础泛型类和基础泛型接口只需要写一次,就能帮让你少写大量的代码,你也可以不用泛型,这样直接用一个类和一个接口就能实现对user数据的处理。
关系图例:最后用户调用的是UserService。
在这里插入图片描述

代码实例:同样应用泛型类

package com.two.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.two.dao.BaseDao;
import com.two.entity.User1;
import com.two.service.BaseService;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @author lhn
 * 数据层公共实现类
 */
@Service
public abstract class BaseServiceImpl<T> implements BaseService<T> {
    private static final Logger logger = LoggerFactory.getLogger(BaseServiceImpl.class);
    protected abstract BaseDao<T> getMapper();

    @Override
    public boolean insert(T entity)  {
        boolean falg=false;
        try {
            getMapper().insert(entity);
            falg=true;
        } catch (Exception e) {
            logger.error("新增"+getClassName(entity)+"失败!原因是:",e);
        }
        return falg;
    }
    @Override
    public boolean update(T entity){
        boolean falg=false;
        try {
            getMapper().update(entity);
            falg=true;
        } catch (Exception e) {
            logger.error("更新"+getClassName(entity)+"失败!原因是:",e);
        }
        return falg;
    }

    @Override
    public boolean deleteByPrimaryKey(int id)  {
        boolean falg=false;
        try {
            getMapper().deleteByPrimaryKey(id);
            falg=true;
        } catch (Exception e) {
            logger.error("id:"+id+"删除失败!原因是:",e);
        }
        return falg;
    }

    @Override
    public boolean delete(T entity){
        boolean falg=false;
        try {
            getMapper().delete(entity);
            falg=true;
        } catch (Exception e) {
            logger.error("删除"+getClassName(entity)+"失败!原因是:",e);
        }
        return falg;
    }

    @Override
    public T findByPrimaryKey(int id) {
        T obj = null;
        try {
            obj = getMapper().findByPrimaryKey(id);
        } catch (Exception e) {
            logger.error("id:"+id+"查询失败!原因是:",e);
        }
        return obj;
    }

    @Override
    public T findByEntity(T entity) {
        T obj = null;
        try {
            obj = getMapper().findByEntity(entity);
        } catch (Exception e) {
            logger.error("查询"+getClassName(entity)+"失败!原因是:",e);
        }
        return obj;
    }

    @Override
    public List<T> findByListEntity(T entity) {
        List<T> list = null;
        try {
            Page<?> page = PageHelper.startPage(1,2);
            System.out.println(getClassName(entity)+"设置第一页两条数据!");
            list = getMapper().findByListEntity(entity);
            System.out.println("总共有:"+page.getTotal()+"条数据,实际返回:"+list.size()+"两条数据!");
        } catch (Exception e) {
            logger.error("查询"+getClassName(entity)+"失败!原因是:",e);
        }
        return list;
    }

    @Override
    public List<T> findAll() {
        List<T> list = null;
        try {
            list =  getMapper().findAll();
        } catch (Exception e) {
            logger.error("查询失败!原因是:",e);
        }
        return list;
    }

    @Override
    public Object findByObject(Object obj) {
        Object result = null;
        try {
            result = getMapper().findByObject(obj);
        } catch (Exception e) {
            logger.error("查询"+obj+"失败!原因是:",e);
        }
        return result;
    }

    @Override
    public T findByUsername(String username){
        T obj = null;
        try {
            obj = getMapper().findByUsername(username);
        } catch (Exception e) {
            logger.error("查询"+username+"失败!原因是:",e);
        }
        return obj;
    }

    private String getClassName(T t){
        String str="";
        if(t instanceof User1){
            str="User";
        }
        return str;
    }
}

UserServiceImpl用户服务实现类,这个类继承了基础服务实现类,并且实现了用户服务接口,通过接口访问服务,使程序具有更好的封装性。这个类注入了dao类,并且重写getMapper()方法将注入的dao类提供给service中的方法进行使用如果你能很好的理解spring的依赖注入,这些代码就很好理解

package com.two.service.impl;

import com.two.dao.BaseDao;
import com.two.dao.UserDao2;
import com.two.entity.User;
import com.two.entity.User1;
import com.two.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends BaseServiceImpl<User1>  implements UserService {
    @Autowired
    public UserDao2 userDao;

    @Override
    protected BaseDao<User1> getMapper() {
        return this.userDao;
    }

}

基础接口类:

package com.two.service;

import java.util.List;


public interface BaseService<T> {
    /**
     * 插入数据
     *
     * @param entity
     * @return
     * @throws
     */
    boolean insert(T entity) ;

    /**
     * 更新数据
     *
     * @param entity
     * @return
     * @throws
     */
    boolean update(T entity) ;

    /**
     * 根据ID删除数据
     * @param id
     * @throws Exception
     * @throws
     */
    boolean deleteByPrimaryKey(int id) ;

    /**
     * 删除数据
     * @param entity
     * @throws Exception
     * @throws
     */
    boolean delete(T entity) ;


    /**
     * 根据id查询单个记录
     *
     * @param id
     * @return
     * @throws Exception
     * @throws
     */
    T findByPrimaryKey(int id);

    /**
     * 根据对象查询单个记录
     *
     * @param entity
     * @return
     * @throws Exception
     * @throws
     */
    T findByEntity(T entity);



    /**
     * 根据对象查询多条记录
     * @param entity
     * @return
     */
    List<T> findByListEntity(T entity);

    /**
     * 查询所有记录
     * @return
     */
    List<T> findAll();

    /**
     * 根据用户名查询对象
     * @param username
     * @return
     */
    T findByUsername(String username);

    /**
     * 根据对象查询信息
     *
     * @param obj
     * @return
     * @throws Exception
     * @throws
     */
    Object findByObject(Object obj);
}

用户服务接口:

package com.two.service;

import com.two.entity.User1;
import org.springframework.stereotype.Service;

@Service
public interface UserService extends BaseService<User1>{
}

4.总结

整个User数据处理的功能就实现了,在controller类中,同样的用@Autowired注解将service组件(bean)注入进行使用。这里我用的是mybatis,你也可以使用jpa或者其他。

欢迎提问!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值