首先是核心配置文件daoContext.xml


[html] view plain copy

<?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里面的内容非常简单

[plain] view plain copy

driverClassName=oracle.jdbc.driver.OracleDriver  

url=jdbc:oracle:thin:@127.0.0.1:1521:orcl  

username=myname  

password=mypassword  

然后我们需要一个实体类,就是数据库的表名,我叫做MyEntity,代码如下


[java] view plain copy

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;  

    }  

}  

有了表。我们还需要对表的操作。

这就更加简单了


[java] view plain copy

public interface MyEntityRepository extends JpaRepository<MyEntity, Long> {  

[java] view plain copy

//里面可以写各种复杂函数。暂时我们就先用一些基本的操作,所以无需写任何代码  

}  


最后在我们的服务类中进行测试

[java] view plain copy

public class MyService {  

    @Autowired  

    MyEntityRepository myEntityRepository;  

    public String processCommand(String anything)  

    {  

        String str = "hello";  

        List<MyEntity> myEntityList = myEntityRepository.findAll();  

        return str;  

    }  

}  


一切OK。成功拿到了表里数据(表里的数据可以用工具直接写入数据库)

真的是太轻松了。都没几行代码。如果有人设计好了数据库,用hibernate是可以直接生成MyEntity的类,也是说。对数据库进行操作,基本不用写啥代码,增删改查都有了。


最后补下缺失的代码


[java] view plain copy

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;  

    }  

}