1. 程式人生 > >【SpringMvc】從零開始學SpringMvc之資料庫(二)

【SpringMvc】從零開始學SpringMvc之資料庫(二)

大家好,在上一篇中,我們介紹了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

你的認可,是我堅持更新部落格的動力,如果覺得有用,就請點個贊,謝謝