SpringMvc

【SpringMvc】从零开始学SpringMvc之数据库(二)

2018-11-01  本文已影响0人  欢子3824

前言

大家好,在上一篇中,我们介绍了SpringMvc 的搭建,这篇我们来看下SpringMvc连接数据库。

准备

首先, 需要安装MysqlNavicat(或者类似软件)、有一点sql基础,了解一点mybatis 语法

#mysql jdbc
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
jdbc.uid=root
jdbc.pwd=123456
<context:property-placeholder
        location="classpath*:db.properties" />
<bean id="datasource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!-- 数据库驱动 -->
        <property name="driverClassName"
            value="com.mysql.jdbc.Driver" />
        <!-- 连接数据库的URL 数据库名为已经创建好的User -->
        <property name="url" value="${jdbc.url}" />
        <!-- 连接数据库的用户名 -->
        <property name="username" value="${jdbc.uid}" />
        <!-- 连接数据的密码 -->
        <property name="password" value="${jdbc.pwd}" />
    </bean>
<bean id="sqlSessionFactory"
        class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据源 -->
        <property name="dataSource" ref="datasource"></property>
        <!-- 别名 -->
        <property name="typeAliasesPackage" value="com.test.model"></property>
        <!-- sql映射文件路径 -->
        <property name="mapperLocations"
            value="classpath*:com/test/mapper/*Mapper.xml"></property>
    </bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--指定会话工厂,如果当前上下文中只定义了一个则该属性可省去 -->
        <property name="sqlSessionFactoryBeanName"
            value="sqlSessionFactory"></property>
        <!-- 指定要自动扫描接口的基础包,实现接口 -->
        <property name="basePackage" value="com.test.mapper"></property>
    </bean>
<bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="datasource"></property>
    </bean>
        private String id;
    private String username;
    private String password;
    private String phone;
    private String email;
    private String createTime;
    private String editTime;
public interface UserDao {
    
    public List<UserModel> getAllUsers();

    public UserModel getUserById(@Param("id") String id);

    public int delete(String id);

    public int add(UserModel entity);

    public int update(UserModel entity);

    
}

UserMapper.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">
<!--命名空间应该是对应接口的包名+接口名 -->
<mapper namespace="com.test.mapper.UserDao">
    <!--id应该是接口中的方法,结果类型如没有配置别名则应该使用全名称 -->
    

    <select id="getAllUsers" resultType="UserModel">
        select
        id,username,password,phone,email,createTime,editTime from user
    </select>
    <!--获得用户对象通过id -->
    <select id="getUserById" resultType="UserModel">
        select
        id,username,password,phone,email,createTime,editTime from user where
        id=#{id}
    </select>

    <!-- 增加 -->
    <insert id="add">
        insert into
        user(username,password,phone,email,createTime,editTime)
        values(#{username},#{password},#{phone},#{email},#{createTime},#{editTime})
    </insert>
    <!-- 删除 -->
    <delete id="delete">
        delete from user where id=#{id}
    </delete>
    <!-- 更新 -->
    <update id="update">
        update user set
        username=#{username},password=#{password},phone=#{phone},email=#{email},editTime=#{editTime}
        where
        id=#{id}
    </update>
</mapper>

Mybatis 中常用的标签有insertdeleleupdateselect,其代表的分别是增、删、改、查,需要注意的是,每个标签的id 需和UserDao 中定义的一致

@Controller
@RequestMapping("/user")
public class UserController  {
    public static final String SUCC_MSG = "请求成功";
    public static final String ERROR_MSG = "请求失败";
    public static final int SUCC_CODE = 1;
    public static final int ERROR_CODE = 0;

    @Autowired
    UserDao userdao;

    /**
     * 返回json
     * 
     * @return
     */
    @ResponseBody
    @RequestMapping("/addUser")
    public BaseModel addUser(UserModel user) {
        
                int code = userdao.add(user);
                if (code == 0) {
                    return makeModel(code, "添加失败");
                } else {
                    return makeModel(code, "添加成功");
                }
    }
    @ResponseBody
    @RequestMapping("/updateUser")
    public BaseModel updateUser(UserModel user) {
            int code = userdao.update(user);
            if (code == 0) {
                return makeModel(ERROR_CODE, "更新失败");
            } else {
                return makeModel(SUCC_CODE, "更新成功");
            }
    }

    @ResponseBody
    @RequestMapping("/getUser")
    public BaseModel getUser() {
            return makeModel(SUCC_CODE, SUCC_MSG, userdao.getAllUsers());
    }

    @ResponseBody
    @RequestMapping("/deleteUser")
    public BaseModel deleteUser(String id) {
        if (TextUtils.isEmpty(id)) {
            return makeModel(ERROR_CODE, "用户id不能为空");
        } else {
            int code = userdao.delete(id);
            if (code == 0) {
                return makeModel(code, "删除失败");
            } else {
                return makeModel(code, "删除成功");
            }

        }
    }
        /**
     * 
     * @param code
     * @param msg
     * @return
     */
    public BaseModel makeModel(int code, String msg) {
        BaseModel model = new BaseModel();
        model.setCode(code);
        model.setMsg(msg);
        return model;
    }
/**
     * 
     * @param code
     * @param msg
     * @param data
     * @return
     */
    public BaseModel makeModel(int code, String msg, Object data) {
        BaseModel model = new BaseModel();
        model.setCode(code);
        model.setData(data);
        model.setMsg(msg);
        return model;
    }
    
}

有没有同学注意到,我们的addUser方法中,传入的是UserModel 对象,而不是具体的参数,为什么我们传具体的参数却可以添加成功? 这是因为SpringMvc 已经帮我们完成了自动装箱这个过程。看到这里,还不快来试试?

最后献上源码Github

你的认可,是我坚持更新博客的动力,如果觉得有用,就请点个赞,谢谢

上一篇下一篇

猜你喜欢

热点阅读