@Entity //聲明實體 @Table(name="tbl_user") //對應表 public class UserModel { //定義主鍵 @Id private Integer uuid; private String name; private Integer age; //省略getter/setter }
nDAO的接口java
public interface UserRepository extends JpaRepository<UserModel, Integer>{ //空的,能夠什麼都不用寫 }
@Service @Transactional public class Client { @Autowired private UserRepository ur; public void testAdd(UserModel um){ ur.save(um); } public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); Client c = (Client)ctx.getBean("client"); UserModel um = new UserModel(); um.setAge(1); um.setName("張三"); um.setUuid(1); c.testAdd(um); } }
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd "> <!--定義服務層代碼包存放路徑,包下自動找@service註釋的類--> <context:component-scan base-package="com....."> <context:exclude-filter type="annotation「 expression="org.springframework.stereotype.Controller"/> </context:component-scan> <aop:aspectj-autoproxy proxy-target-class="true"/> <!-- 開啓註解事務 只對當前配置文件有效 --> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/> <!--定義repository接口存放目錄--> <!--定義接口實現的後綴,一般用Impl--> <!--定義實體工廠的引用--> <!--定義事務管理器的引用--> <jpa:repositories base-package="com......repository" repository-impl-postfix="Impl" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager"> </jpa:repositories> <!--定義實體工廠bean--> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="......" ref="....."/> <property name="......" value="......"/> <property name="......."> <bean class="........"/> </property> </bean> <!--事務管理器配置--> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> </beans>