1. 程式人生 > >JAVA操作資料庫一(Spring data jpa)

JAVA操作資料庫一(Spring data jpa)

總的來說,JAVA操作資料庫還是相當方便的。

首先是核心配置檔案daoContext.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:jdbc="http://www.springframework.org/schema/jdbc"
	   xmlns:c="http://www.springframework.org/schema/c"
	   xmlns:context="http://www.springframework.org/schema/context"
	   xmlns:p="http://www.springframework.org/schema/p"
	   xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	   xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

	<jpa:repositories base-package="db,service" />
	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
		  p:dataSource-ref="dataSource"
		  p:persistenceUnitName="mypersistest"
		  p:packagesToScan="entity"
		  p:jpaVendorAdapter-ref="jpaVendorAdapter"/>
	<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
		<property name="database" value="ORACLE" />
		<property name="showSql" value="true" />
		<property name="generateDdl" value="true" />
	</bean>

	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
	/>

	<!-- PropertyPlaceholderConfigurer是一個容器後處理器,它會讀取
	屬性檔案資訊,並將這些資訊設定成Spring配置檔案的資料。 -->
	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:my.properties</value>
				<!-- 如果有多個屬性檔案,依次在下面列出來 -->
				<!--value>dbconn.properties</value-->
			</list>
		</property>
	</bean>
	<!-- Simple implementation of the standard JDBC DataSource interface,
       configuring the plain old JDBC DriverManager via bean properties -->
	<bean id="dataSource" class="oracle.jdbc.pool.OracleDataSource">
		<property name="URL" value="${url}" />
		<property name="user" value="${username}" />
		<property name="password" value="${password}" />
		<property name="implicitCachingEnabled" value="true"/>
		<property name="fastConnectionFailoverEnabled" value="true"/>
	</bean>

</beans>

my.properties裡面的內容非常簡單
driverClassName=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
username=myname
password=mypassword

然後我們需要一個實體類,就是資料庫的表名,我叫做MyEntity,程式碼如下

import javax.persistence.*;
import java.math.BigDecimal;

@Entity
public class MyEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "prooduct_id_seq")
    @SequenceGenerator(name="prooduct_id_seq", sequenceName = "PRODUCT_ID_SEQ", allocationSize = 100)
    private Integer id;

    @Version
    private Integer version;

    private String testString;
    private BigDecimal testNumber;

    public Integer getId() {
        return id;
    }

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

    public Integer getVersion() {
        return version;
    }

    public void setVersion(Integer version) {
        this.version = version;
    }

    public String getTestString() {
        return testString;
    }

    public void setTestString(String testString) {
        this.testString = testString;
    }

    public BigDecimal getTestNumber() {
        return testNumber;
    }

    public void setTestNumber(BigDecimal testNumber) {
        this.testNumber = testNumber;
    }
}
有了表。我們還需要對錶的操作。

這就更加簡單了

public interface MyEntityRepository extends JpaRepository<MyEntity, Long> {
//裡面可以寫各種複雜函式。暫時我們就先用一些基本的操作,所以無需寫任何程式碼
}

最後在我們的服務類中進行測試
public class MyService {
    @Autowired
    MyEntityRepository myEntityRepository;
    public String processCommand(String anything)
    {
        String str = "hello";
        List<MyEntity> myEntityList = myEntityRepository.findAll();
        return str;
    }
}

一切OK。成功拿到了表裡資料(表裡的資料可以用工具直接寫入資料庫)

真的是太輕鬆了。都沒幾行程式碼。如果有人設計好了資料庫,用Hibernate是可以直接生成MyEntity的類,也是說。對資料庫進行操作,基本不用寫啥程式碼,增刪改查都有了。

最後補下缺失的程式碼

import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import service.MyService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@EnableWebMvc
@RequestMapping(value = "mytest")
public class MyController {
    public MyController() {
        wac = ContextLoader.getCurrentWebApplicationContext();
    }
    WebApplicationContext wac;
    private static final Logger logger = LoggerFactory.getLogger(MyController.class);
    @RequestMapping(value = "/{anything}",  method = RequestMethod.POST, produces="application/json;charset=UTF-8")
    public Object myServiceControl(HttpServletRequest request, HttpSession session, @PathVariable String anything)
    {
        String jsonRet = "hello";
        logger.info(request.getMethod());
        logger.info("anything is " + anything ) ;
        try{
            MyService  myService = (MyService)wac.getBean("myService");
            jsonRet = myService.processCommand(anything);
        }catch(Exception e){
            JSONObject jsonObject = new JSONObject();
            e.printStackTrace();
            jsonObject.put("result" , "-1");
            jsonObject.put("desc" , e.toString());
            return jsonObject.toString();
        }
        logger.info("end");
        logger.info(jsonRet);
        return jsonRet;
    }
}

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>TestDataBaseGroup2</groupId>
  <artifactId>TestDataBaseArt2</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>TestDataBaseArt Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <!-- oracle -->
    <dependency>
      <groupId>com.oracle</groupId>
      <artifactId>ojdbc6</artifactId>
      <version>11.2.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>6.0.5</version>
    </dependency>

    <!-- spring -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.4.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.3.4.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>4.3.4.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.4.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.4.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-jpa</artifactId>
      <version>1.10.6.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.session/spring-session -->
    <dependency>
      <groupId>org.springframework.session</groupId>
      <artifactId>spring-session</artifactId>
      <version>1.2.2.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-elasticsearch -->
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-elasticsearch</artifactId>
      <version>2.0.5.RELEASE</version>
    </dependency>
    <!-- hibernate -->
    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->


    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.2.5.Final</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0 -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-c3p0</artifactId>
      <version>5.2.5.Final</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.1.8</version>
    </dependency>
    <!-- servlet -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.inject/javax.inject -->
    <dependency>
      <groupId>javax.inject</groupId>
      <artifactId>javax.inject</artifactId>
      <version>1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <version>1.4.193</version>
    </dependency>

    <!-- json -->
    <dependency>
      <groupId>net.sf.json-lib</groupId>
      <artifactId>json-lib</artifactId>
      <version>2.3</version>
      <classifier>jdk15</classifier>
    </dependency>
  </dependencies>
  <build>
    <finalName>OnlyMyTest</finalName>
  </build>
</project>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
        version="3.1">
  <display-name>Archetype Created Web Application</display-name>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml,classpath:daoContext.xml</param-value>
  </context-param>

  <servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:mvc-dispatcher-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns="http://www.springframework.org/schema/beans"
	   xmlns:p="http://www.springframework.org/schema/p"
	   xmlns:c="http://www.springframework.org/schema/c"
	   xmlns:tx="http://www.springframework.org/schema/tx"
	   xmlns:task="http://www.springframework.org/schema/task"
	   xmlns:aop="http://www.springframework.org/schema/aop"
	   xmlns:context="http://www.springframework.org/schema/context"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans
	   
	   http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	   http://www.springframework.org/schema/tx
	   http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	   http://www.springframework.org/schema/aop
	   http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
	   http://www.springframework.org/schema/task
       http://www.springframework.org/schema/task/spring-task-3.1.xsd 
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context.xsd">

	<!-- 定義Service元件,並將DAO元件注入Service元件 -->
	<bean id="myService" class="service.MyService"
	/>
	<context:annotation-config />
</beans>