Skip to content

JEE JPA Discriminator

2015-09-12 17:04:57

Here you will find simple example of JPA Discriminator together with JAX-RS and Jboss 8.

DataBase In this example we will use PostgreSQL as a Data Base. You have to create new data base "test2".

Jboss configuration - standalone.xml

Next you have to update your standalone.xml

<datasource enabled='"true"' jndi-name='"java:jboss/datasources/ExamplePgDS2"' jta='"true"' pool-name='"ExamplePgDS2"' use-ccm='"true"' use-java-context='"true"'>
<check-valid-connection-sql>SELECT 1</check-valid-connection-sql>

If this is your first time when you use postgresql, you have to add postgresql-9.2-1003.jdbc4.jar to /modules/system/layers/base/org/postgresql/main/ in jboss directory. This file you can find on my github.

What next? you have to configure / connect your app with db You can do this by adding persistence.xml to /src/main/resources/META-INF/persistence.xml

<persistence http:="""" ns="" persistence="" persistence_2_0.xsd&quot;="" version='"2.0"' xml="" xmlns='""' xmlns:xsi='""' xsi:schemalocation='"'>
<persistence-unit name='"ExamplePgDS"' transaction-type='"JTA"'>
<property name='"hibernate.dialect"' value='"org.hibernate.dialect.PostgreSQLDialect"'></property>
<property name='""' value='"create-drop"'></property>

ah, I know, XML hell, ok we can switch to java part


package pl.btbw.persistent.entities;

import pl.btbw.web.dto.PostDto;

import javax.persistence.*;

@Table(name = "post")
@DiscriminatorColumn(name = "distype", discriminatorType = DiscriminatorType.STRING)
        @NamedQuery(name = "Post.all", query = "SELECT p FROM Post p WHERE distype = 'POST'")
public class Post {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    protected int id;

    @Column(name = "name")
    protected String name;

    public Post() {

    public Post(String name) { = name;

    public PostDto asDto() {
        return new PostDto(id, name);
package pl.btbw.persistent.entities;

import pl.btbw.web.dto.ArticleDto;

import javax.persistence.*;

@Table(name = "article")
        @NamedQuery(name = "Article.all", query = "SELECT p FROM Article p WHERE distype = 'ARTICLE'")
public class Article extends Post {

    @Column(name = "category")
    private String category;

    public Article() {

    public Article(String name, String category) { = name;
        this.category = category;

    public ArticleDto asDto() {
        return new ArticleDto(id, name, category);

as you see Article extends Post. Both entities use one table "post"

We have possibility to distinguish them by simple trick with @DiscriminatorColumn and @DiscriminatorValue anotations.

and that is all, our table "post" now have extra column "distype" where for post entity system will add "POST" value, for article entity "ARTICLE" value.

we can use this proper to adjust queries and fetch only what we need

of course full example you can find on github