Java操作資料庫Spring(1)
阿新 • • 發佈:2022-05-04
首先是核心配置檔案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;
}
}