码迷,mamicode.com
首页 > 编程语言 > 详细

使用Maven开发一个简单的SpringData

时间:2017-09-16 00:34:15      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:return   color   images   repo   maven   image   uil   pid   cat   

1:创建Maven项目

2:添加依赖(修改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>com.gx</groupId>
  <artifactId>SpringData</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringData Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.38</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>4.3.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.5.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.8.0.RELEASE</version>
    </dependency>
    <!-- hibernate-entity -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>4.3.6.Final</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>SpringData</finalName>
  </build>
</project>

3:创建配置文件spring-data-beans.xml(名字随便取)内容如下

<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: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.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="username" value="root" />
        <property name="password" value="root" />
        <property name="url" value="jdbc:mysql://localhost:3307/test" />
    </bean>
    
    <!-- 配置EntityManagerFactory -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 设置jpa适配器 -->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
        </property>
        <!-- 采用注解的方式,扫描包下面的java类 -->
        <property name="packagesToScan" value="com.gx"/>
        <!-- jpa的相关配置 -->
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <prop key="hibernate.show_sql">true</prop><!--执行的时候是否显示SQL-->
                <prop key="hibernate.format_sql">true</prop><!--执行的时候SQL是否格式化,如果不格式化的话得到的SQL语句就是一条,没有换行,不便阅读-->
                <prop key="hibernate.hbm2ddl.auto">update</prop><!--如果没有是否创建-->
            </props>
        </property>
    </bean>

</beans>

4:创建测试类com.gx.SpringData测试配置文件spring-data-beans.xml里面配置的EntityManagerFactory是否成功

4.1:创建一个数据库里面没有的表的实体类(比如说User)内容如下

package com.gx.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/*
 * 这个Entity的注解会告诉配置文件这是一个实体类
 * 配置文件会根据EntityManagerFactory来判断是否有这个表
 * 如果没有回字段生成
 */
@Entity
public class User {
    /*最好使用封装之后的类型
     * 因为在后面的类使用的时候需要用到泛型Repository<User, Integer>,这里的Integer就是主键Id
     */
    private Integer id;
    private String name;
    private Integer age;
    @GeneratedValue//这个注解是告诉配置文件这个id是自增的
    @Id//这个注解是告诉配置文件这是一个id
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    /*这个注解是设置表user里面的name字段的长度为20,默认不为空
     * 如果不设置的话默认是255
     */
    @Column(length=20,nullable=false)
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
    
}

4.2:创建测试类com.gx.SpringData内容如下

package com.gx;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringData {
    //获取上下文
    private ApplicationContext ctx = null;
    @Before
    public void setup(){
        System.out.println("setup is working......");
        ctx = new ClassPathXmlApplicationContext("spring-data-beans.xml");
    }
    @After
    public void destory(){
        ctx = null;
        System.out.println("destory is working......");
    }
    @Test
    public void testEntityManagerFctory(){
        
    }
}

4.3:测试结果

技术分享

5:在配置文件里面添加配置

    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <!--配置支持注解的事务-->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!--配置spring data 需要扫描的包-->
    <jpa:repositories base-package="com.gx" entity-manager-factory-ref="entityManagerFactory"/>

    <!--在这个配置里面的内容spring都能够自动找到,更方便-->
    <context:component-scan base-package="com.gx"/>

6:创建接口com.gx.repository.UserRepository

package com.gx.repository;

import org.springframework.data.repository.Repository;

import com.gx.entity.User;

public interface UserRepository extends Repository<User, Integer>{

    public User findByName(String name);
}

7:测试(在数据库中添加数据并在测试类里面查询)修改测试类com.gx.SpringData内容如下

技术分享

package com.gx;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.gx.entity.User;
import com.gx.repository.UserRepository;

public class SpringData {
    //获取上下文
    private ApplicationContext ctx = null;
    private UserRepository userRepository = null;
    @Before
    public void setup(){
        System.out.println("setup is working......");
        ctx = new ClassPathXmlApplicationContext("spring-data-beans.xml");
        userRepository = ctx.getBean(UserRepository.class);
    }
    @After
    public void destory(){
        ctx = null;
        System.out.println("destory is working......");
    }
    
    @Test
    public void testEntityManagerFctory(){
        
    }
    
    @Test
    public void findByName(){
        User user = userRepository.findByName("minuobaci");
        System.out.println(user);
    }
}

 8:测试结果

技术分享

 

使用Maven开发一个简单的SpringData

标签:return   color   images   repo   maven   image   uil   pid   cat   

原文地址:http://www.cnblogs.com/minuobaci/p/7524888.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!