Spring Boot&JPA&Hibernate&Oracle

在本教程中,我们将展示如何创建一个Spring Boot应用程序,该应用程序通过Hibernate与Oracle数据源进行通信。

先决条件:

  • Eclipse IDE(最新版本)
  • Maven的4
  • Java 1.8

1-创建Maven项目

打开eclipse,然后创建一个新的Maven项目并将其命名为SpringBootHibernate

在本教程的最后,我们将获得以下项目结构:

2-pom.xml

通过添加以下父依赖项在pom.xml中配置Spring Boot:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.10.RELEASE</version>
</parent>

然后添加spring-boot-starter依赖性,以将我们的应用程序作为独立的jar应用程序运行:

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
</dependency>

现在,为了利用Spring数据jpa和休眠状态,我们只需添加spring-boot-starter-data-jpa作为依赖项:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

一旦在项目中包含Spring Boot Starter JPA ,我们就会从各种各样的依赖项中获得以下功能:

  • 自动配置内存中嵌入式数据库,使您无需设置数据库即可运行应用程序。
  • 自动导入JPA APIHibernate,添加此依赖项将自动导入JPA API并使用Hibernate作为默认实现。
  • application.properties自动读取数据源和休眠配置
  • 自动创建表实体并自动执行import.sql。

这是整个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.programmer.gate</groupId>
  <artifactId>SpringBootHibernate</artifactId>
  <packaging>jar</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringBootHibernate</name>
  
  <properties>
       <maven.compiler.source>1.8</maven.compiler.source>
       <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.10.RELEASE</version>
    </parent>
    
  <dependencies>
  
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    
  </dependencies>
  
  <build>
      <plugins>
          <plugin>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-maven-plugin</artifactId>
          </plugin>
      </plugins>
  </build>
  
</project>

3-将Oracle驱动程序添加到类路径

在本教程中,我们将覆盖Spring Boot提供的默认内存数据库,并使用我们自己的oracle数据库。

为此,我们在WEB-INF / lib下添加“ oracle-ojdbc6-11.2.0.3.jar” ,并在类路径中对其进行定义。

4- application.properties

配置oracle数据源并在application.properties中休眠:

# create and drop tables and sequences, loads import.sql
spring.jpa.hibernate.ddl-auto=create-drop
 
# Oracle settings
spring.datasource.url=jdbc:oracle:thin:@localhost:1522:orcl
spring.datasource.username=HIBERNATE_TEST
spring.datasource.password=HIBERNATE_TEST
spring.datasource.driver.class=oracle.jdbc.driver.OracleDriver
 
# logging
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n
logging.level.org.hibernate.SQL=debug

5个实体

我们的实体代表一个球员和一个具有一对多关系的球队,每个球队可以有很多球员,而一个球员一次只能与一个球队比赛。

因此,我们在com.programmer.gate.model包下创建实体:

播放器

package com.programmer.gate.model;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
 
@Entity
public class Player {
 
    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "player_Sequence")
    @SequenceGenerator(name = "player_Sequence", sequenceName = "PLAYER_SEQ")
    private Long id;
 
    @Column(name = "name")
    private String name;
 
    @Column(name = "num")
    private int num;
 
    @Column(name = "position")
    private String position;
    
    @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn(name = "team_id", nullable = false)
        private Team team;
    
    public Player() {
    }
        // getters/setters
}

Team.java

package com.programmer.gate.model;
 
import java.util.List;
 
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
 
@Entity
public class Team {
 
    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "team_Sequence")
    @SequenceGenerator(name = "team_Sequence", sequenceName = "TEAM_SEQ")
    private Long id;
 
    @Column(name = "name")
    private String name;
 
    @OneToMany(cascade = CascadeType.ALL,
            fetch = FetchType.EAGER,
            mappedBy = "team")
    private List<Player> players;
    
    public Team() {
    }
 
        // getters/setters
}

由于我们在application.properties中设置了spring.jpa.hibernate.ddl-auto = create-drop ,因此我们的应用程序将在数据库中自动创建PlayerTeam实体以及它们的顺序和约束。

我们的应用程序还将在类路径中查找import.sql并执行(如果找到)。

在我们的示例中,我们在src / main / resources下定义import.sql ,以便用静态数据填充表:

insert into Team (id,name) values(1,'Barcelona');
 
insert into Player (id, team_id, name, num, position) values(1,1,'Lionel Messi', 10, 'Forward');
insert into Player (id, team_id, name, num, position) values(2,1,'Andreas Inniesta', 8, 'Midfielder');
insert into Player (id, team_id, name, num, position) values(3,1,'Pique', 3, 'Defender');

6-存储库

我们在com.programmer.gate.repository下定义我们的存储库接口。 每个存储库都扩展了Spring CrudRepository ,它为基本的find,save和delete方法提供了默认实现,因此我们不必为它们定义实现类。

播放器存储库

package com.programmer.gate.repository;
 
import java.util.List;
 
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
 
import com.programmer.gate.model.Player;
 
@Repository
public interface PlayerRepository extends CrudRepository<Player, Long> {
 
    List<Player> findByTeamId(long teamId);
}

团队资料库

package com.programmer.gate.repository;
 
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
 
import com.programmer.gate.model.Team;
 
@Repository
public interface TeamRepository extends CrudRepository<Team, Long> {
 
    Team findByPlayers(long playerId);
}

7-服务

现在,我们定义服务类来保存应用程序的业务逻辑,我们的服务公开两种方法: getAllTeamPlayers()addBarcelonaPlayer()如果您不喜欢Barcelona :D, 只需将其重命名为您喜欢的俱乐部 ),我们的服务层直接与存储库层通信。

SoccerService.java

package com.programmer.gate.service;
 
import java.util.List;
 
public interface SoccerService {
    public List<String> getAllTeamPlayers(long teamId);
    public void addBarcelonaPlayer(String name, String position, int number);
}

足球服务Impl

package com.programmer.gate.service;
 
import java.util.ArrayList;
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import com.programmer.gate.model.Player;
import com.programmer.gate.model.Team;
import com.programmer.gate.repository.PlayerRepository;
import com.programmer.gate.repository.TeamRepository;
 
@Service
public class SoccerServiceImpl implements SoccerService {
 
    @Autowired
    private PlayerRepository playerRepository;
    @Autowired
    private TeamRepository teamRepository;
 
    public List<String> getAllTeamPlayers(long teamId) {
        List<String> result = new ArrayList<String>();
        List<Player> players = playerRepository.findByTeamId(teamId);
        for (Player player : players) {
            result.add(player.getName());
        }
 
        return result;
    }
 
    public void addBarcelonaPlayer(String name, String position, int number) {
        
        Team barcelona = teamRepository.findOne(1l);
        
        Player newPlayer = new Player();
        newPlayer.setName(name);
        newPlayer.setPosition(position);
        newPlayer.setNum(number);
        newPlayer.setTeam(barcelona);
        playerRepository.save(newPlayer);
    }
}

8- Application.java

最后一步是创建Spring Boot初始化程序,这是我们应用程序的入口。 我们在com.programmer.gate下定义Application.java

package com.programmer.gate;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
import com.programmer.gate.service.SoccerService;
 
@SpringBootApplication
public class Application implements CommandLineRunner{
    
    @Autowired
    SoccerService soccerService;
    
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    
    @Override
    public void run(String... arg0) throws Exception {
        
        soccerService.addBarcelonaPlayer("Xavi Hernandez", "Midfielder", 6);
        
        List<String> players = soccerService.getAllTeamPlayers(1);
        for(String player : players)
        {
            System.out.println("Introducing Barca player => " + player);
        }
    }
}

PS:值得一提的是,Spring Boot应用程序会自动读取并创建相对于初始化程序类所在位置的相同或子包中定义的实体,存储库和服务,因此如果我们在不同的包下定义Application.java,我们需要明确指定模型,存储库和服务的包。

输出:

当将应用程序作为标准Java应用程序运行时,我们将在控制台中获得以下输出。

2018-04-13 14:54:47 DEBUG org.hibernate.SQL - create sequence player_seq start with 1 increment by 1
2018-04-13 14:54:47 DEBUG org.hibernate.SQL - create sequence team_seq start with 1 increment by 1
2018-04-13 14:54:47 DEBUG org.hibernate.SQL - create table player (id number(19,0) not null, name varchar2(255 char), num number(10,0), position varchar2(255 char), team_id number(19,0) not null, primary key (id))
2018-04-13 14:54:47 DEBUG org.hibernate.SQL - create table team (id number(19,0) not null, name varchar2(255 char), primary key (id))
2018-04-13 14:54:47 DEBUG org.hibernate.SQL - alter table player add constraint FKdvd6ljes11r44igawmpm1mc5s foreign key (team_id) references team
2018-04-13 14:54:47 INFO  o.h.tool.hbm2ddl.SchemaExport - HHH000476: Executing import script '/import.sql'
2018-04-13 14:54:47 INFO  o.h.tool.hbm2ddl.SchemaExport - HHH000230: Schema export complete
2018-04-13 14:54:47 INFO  o.s.o.j.LocalContainerEntityManagerFactoryBean - Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-04-13 14:54:48 INFO  o.s.j.e.a.AnnotationMBeanExporter - Registering beans for JMX exposure on startup
2018-04-13 14:54:48 DEBUG org.hibernate.SQL - select team0_.id as id1_1_0_, team0_.name as name2_1_0_, players1_.team_id as team_id5_0_1_, players1_.id as id1_0_1_, players1_.id as id1_0_2_, players1_.name as name2_0_2_, players1_.num as num3_0_2_, players1_.position as position4_0_2_, players1_.team_id as team_id5_0_2_ from team team0_, player players1_ where team0_.id=players1_.team_id(+) and team0_.id=?
2018-04-13 14:54:48 DEBUG org.hibernate.SQL - select player_seq.nextval from dual
2018-04-13 14:54:48 DEBUG org.hibernate.SQL - insert into player (name, num, position, team_id, id) values (?, ?, ?, ?, ?)
2018-04-13 14:54:48 INFO  o.h.h.i.QueryTranslatorFactoryInitiator - HHH000397: Using ASTQueryTranslatorFactory
2018-04-13 14:54:48 DEBUG org.hibernate.SQL - select player0_.id as id1_0_, player0_.name as name2_0_, player0_.num as num3_0_, player0_.position as position4_0_, player0_.team_id as team_id5_0_ from player player0_, team team1_ where player0_.team_id=team1_.id(+) and team1_.id=?
 
Introducing Barca player => Lionel Messi
Introducing Barca player => Andreas Inniesta
Introducing Barca player => Pique
Introducing Barca player => Xavi Hernandez
 
2018-04-13 14:54:49 INFO  com.programmer.gate.Application - Started Application in 4.213 seconds (JVM running for 4.555)

9-源代码

您可以从此存储库下载源代码: spring-boot-jpa-hibernate

翻译自: https://www.javacodegeeks.com/2018/04/spring-boot-jpa-hibernate-oracle.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值