SpringMVC+hibernate小實例(註解式)

        週六了,趁着上午暈暈乎乎的時光寫個小實例,再熟悉一下SpringMVC,爲今後可能學習到的spring boot做點鋪墊。不說了,直接擼代碼吧。

        如下是工程的結構:

                 

        首先用eclipse創建一個maven工程,然後修改一下WEB-INF下的web.xml文件,如下:

<!DOCTYPE web-app PUBLIC  
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"  
 "http://java.sun.com/dtd/web-app_2_3.dtd" >  
  
<web-app>  
  <display-name>Archetype Created Web Application</display-name>  
  <servlet>  
    <servlet-name>springmvc</servlet-name>  
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
    <init-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>/applicationContext.xml</param-value>  
    </init-param>  
    <load-on-startup>1</load-on-startup>  
  </servlet>  
  <servlet-mapping>  
    <servlet-name>springmvc</servlet-name>  
    <url-pattern>/</url-pattern>  
  </servlet-mapping>  
</web-app>

web.xml裏配了servlet,contextConfigLocation是applicatoinContext.xml的位置,load-on-startup是tomcat啓動時就初始化。然後是applicationContext.xml文件,如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-4.3.xsd
	http://www.springframework.org/schema/mvc
	http://www.springframework.org/schema/mvc/spring-mvc.xsd
	http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop.xsd" >


	<context:component-scan base-package="org.test.hitest" />
	<mvc:annotation-driven/>
	<tx:annotation-driven transaction-manager="transactionManager"/>

	
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="#{config[db_driver]}"></property>
		<property name="url" value="#{config[db_url]}"></property>
		<property name="username" value="#{config[db_username]}"></property>
		<property name="password" value="#{config[db_password]}"></property>
	</bean>
    
    

	<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.spatial.dialect.postgis.PostgisPG9Dialect</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
			</props>
		</property>
		<property name="annotatedClasses">
			<list>
				<value>org.test.hitest.db.FileEntry</value>
			</list>
		</property>
	</bean>

	<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	
	<bean id="config" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
		<property name="locations">
			<list>
				<value>classpath:config.properties</value>
			</list>
		</property>
		<property name="fileEncoding" value="UTF-8"></property>
	</bean>
	
</beans>

<context:component-scan base-package="org.test.hitest" />這個配置是告訴spring去掃描這個包下的類,去註冊被@Controller,@Repository等註解標註的類。

<mvc:annotation-driven/>是告訴spring去啓動註解驅動,就是自動去註冊上邊說的Bean到工廠中。

注意,<tx:annotation-driven transaction-manager="transactionManager"/>如果不配這個事務的話,hibernate中的getCurrentSession是會報錯的。

applicationContext.xml中還有有config.properties文件位置,以及hibernate的數據源一些配置。

config.properties文件如下:

db_driver=org.postgresql.Driver
db_url=jdbc:postgresql://localhost:5432/testcenter
db_username=postgres
db_password=postgres

好了,接下來就可以開始寫java代碼了。

我們首先來寫FileEntry類吧,代碼如下:

package org.test.hitest.db;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

import com.vividsolutions.jts.geom.Polygon;

@Entity
@Table(name="fileentry")
public class FileEntry {
	
	@Id
	@GeneratedValue(generator="system-uuid")
	@GenericGenerator(name="system-uuid", strategy="uuid")
	@Column
	private String id;
	
	@Column
	private String name;
	
	@Column
	private String type;
	public FileEntry(){}
	public FileEntry(String name, String type) {
		this.name = name;
		this.type = type;
	}
	
	private Polygon location;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getType() {
		return type;
	}

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

	public Polygon getLocation() {
		return location;
	}

	public void setLocation(Polygon location) {
		this.location = location;
	}
	
}
這個類中用註解的方式告訴了數據庫我們要創建一個名叫fileentry的表,然後又id,name,type,以及location列。GenerateValue和GenericGenerator兩個註解使得主鍵Id的值是由UUID生成的一個不重複唯一值。需要注意的是,由於我在表中添加了Polygon類型的location所以需要讀者安裝postgresql後安裝postgis,然後在數據庫命令行中輸入如下命令:
CREATE EXTENSION postgis

這樣我們創建的postgresql數據庫就支持空間數據了。如果讀者不想安裝postgis的話,就把代碼中lacation屬性以及get/set方法刪除就可以了。

接下來我們寫FileDao類,代碼如下:

package org.test.hitest.db.dao;

import java.util.logging.Logger;

import javax.transaction.Transactional;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.test.hitest.db.FileEntry;

import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Polygon;

@Repository
@Transactional
public class FileDao {
	
	private static Logger logger = Logger.getLogger("com.geovis.icenter.db.FileDao");
	
	@Autowired
	private SessionFactory sessionFactory;
	
	public String addFile(FileEntry fileEntry) {
		sessionFactory.getCurrentSession().save(fileEntry);
		return fileEntry.getId();
	}
	
	public String createDir(String name, String type) {
		FileEntry fileEntry = new FileEntry(name, type);
		return addFile(fileEntry);
	}

	public FileEntry queryFileById(String id) {
		return sessionFactory.getCurrentSession().get(FileEntry.class, id);
	}
	
	public void addPolygonToFiles(String id, Geometry geom) {
		FileEntry fileEntry = sessionFactory.getCurrentSession().get(FileEntry.class, id);
		fileEntry.setLocation((Polygon)geom);
		sessionFactory.getCurrentSession().update(fileEntry);
	}
}

類中的@Autowired是用註解的方式去自動裝配我們在applicationContext.xml中的sessionFactory類。然後類中實現了對數據庫的添加以及查詢的簡單功能。

接下來我們下兩個Response類,一個是QueryResponse,一個是SimpleResponse,代碼如下:

package org.test.hitest.rest.reponse;

import org.test.hitest.db.FileEntry;

public class QueryResponse {

	private int code;
	private String message;
	private FileEntry fileEntry;
	
	public QueryResponse(int code, String message, FileEntry fileEntry) {
		this.code = code;
		this.message = message;
		this.fileEntry = fileEntry;
	}

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public FileEntry getFileEntry() {
		return fileEntry;
	}

	public void setFileEntry(FileEntry fileEntry) {
		this.fileEntry = fileEntry;
	}
}

package org.test.hitest.rest.reponse;

public class SimpleResponse {

	private int code;
	private String message;
	
	public int getCode() {
		return code;
	}
	
	public void setCode(int code) {
		this.code = code;
	}
	
	public String getMessage() {
		return message;
	}
	
	public void setMessage(String message) {
		this.message = message;
	}

	
	public SimpleResponse(int code, String message) {
		super();
		this.code = code;
		this.message = message;
	}
}

這兩個類是我們自己寫的Response,在controller中把Response返回給用戶,用戶會收到一個json。同理,我們也可以寫一個request,可以把瀏覽器(用戶)傳入的json由框架自動轉成request類,代碼如下:

package org.test.hitest.rest.request;

public class FIleCreateRequest {

	private String name;
	private String type;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
}

最後是我們的Controller類,代碼如下:

package org.test.hitest.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.test.hitest.db.FileEntry;
import org.test.hitest.db.dao.FileDao;
import org.test.hitest.rest.reponse.QueryResponse;
import org.test.hitest.rest.reponse.SimpleResponse;
import org.test.hitest.rest.request.FIleCreateRequest;

@RestController
public class DirController {
	
	private static Logger logger = Logger.getLogger("org.test.hitest.controller.DirController");
	
	@Autowired
	private FileDao fileDao;
	
	@RequestMapping(value="/rest/dir/query",method=RequestMethod.GET,produces="application/json")  
    public QueryResponse queryInfo(
    		@RequestParam("id") String id
    		){
		FileEntry fileEntry = fileDao.queryFileById(id);
        return new QueryResponse(0, "succ", fileEntry);
    }
	
	@RequestMapping(value="/rest/dir/create",method=RequestMethod.POST,produces="application/json")
	public SimpleResponse createFile(
			@RequestBody FIleCreateRequest request) {
				
		fileDao.createDir(request.getName(), request.getType());
		
		return new SimpleResponse(0, "success");
		
	}
}

@RestController註解告訴spring這是Controller類,@RequestMapping註解配置了該方法對應的url以及http請求的方法,@RequestBody告訴Spring把收到的json轉成我們自己的request類。我們可以簡單的看一下效果(get方法直接用瀏覽器發送請求,post方法是用postman測試的):



下面是代碼下載的鏈接:

https://download.csdn.net/download/u014627099/10394132


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章