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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21138819/article/details/83624627

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

准备

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

一.下载mysql、mybatis的jar 包,将其复制到lib文件夹下

image.png

二.编写db.properties 数据库配置文件,这里的端口号、账号、密码要和安装Mysql时设置的一致。

#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

三.在applicationContext.xml文件加入如下配置

  • 3.1 引入第二步创建的配置文件
<context:property-placeholder
		location="classpath*:db.properties" />
  • 3.2 配置数据源
<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>
  • 3.3 配置会话工厂bean,指定了Model和mapper 的包名,需要注意,这里配置的包名要和实际代码中保持一致
<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>
  • 3.4 配置自动扫描对象关系映射,这样Spring就可以自动扫描对应关系,需要注意包名
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!--指定会话工厂,如果当前上下文中只定义了一个则该属性可省去 -->
		<property name="sqlSessionFactoryBeanName"
			value="sqlSessionFactory"></property>
		<!-- 指定要自动扫描接口的基础包,实现接口 -->
		<property name="basePackage" value="com.test.mapper"></property>
	</bean>
  • 3.5 声明式事务管理
<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="datasource"></property>
	</bean>

四.创建实体类,创建com.test.model包,并在其下创建UserModel 实体类,get和set 就不贴了

        private String id;
	private String username;
	private String password;
	private String phone;
	private String email;
	private String createTime;
	private String editTime;

五.使用Navicat 创建user库,并在库中建立user 表,属性和UserModel 保持一致

image.png

六.创建com.test.mapper包,并创建UserDao ,UserMapper.xml,注意命名需和3.3中一致

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 中常用的标签有insert、delele、update 、select ,其代表的分别是增、删、改、查,需要注意的是,每个标签的id 需和UserDao 中定义的一致

七.创建UserController

@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;
	}
	
}

其中,@Controller和@RequestMapping("/user")注解我们之前已经说过,前者是标记的类就是一个控制器,后者是用来处理请求地址映射的注解;

@ResponseBody 这个注解添加后,该请求就会以JSON 形式返回

@Autowired 它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。由于我们之前已经配置映射关系,这样它就可以帮我们创建UserDao 对象。

最后,我们在user 表中添加测试数据,然后在浏览器中输入http://localhost:8080/SpringMvc/user/getUser,就可以成功了。

image.png

然后,我们试试添加数据, http://localhost:8080/SpringMvc/user/addUser?username=123&password=123456&phone=187111111111

image.png

我们在Navicat 中查询,发现数据已经添加成功

image.png

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

最后献上源码Github

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

猜你喜欢

转载自blog.csdn.net/qq_21138819/article/details/83624627