Object after persistence and return inconsistent to a dropdown list

Asked

Viewed 96 times

0

Hello folks good afternoon!

Well, briefly I have a problem where I have no idea what might be going on. In my opinion such behavior makes no sense.

I am using Spring MVC + Spring Data to facilitate CRUD operations on my system. I have a page where I register categories, it is something simple, just a field "name" and another to check whether the category is active or not.

Next I have a "Destination Management", who aims to register new destinations. In it I have an association with category in which a dropdown list component is populated. Such a relationship is unidirectional Onetoone factor.

The component is populated normally, below the code of the same:

View:

<f:select path="categories.idCategory">
    <f:option value="-1" label="-- Selecione uma categoria para associação --"/>
    <f:options items="${categoryDropDown}" itemValue="idCategory" itemLabel="ctName"/>
</f:select>

Controller:

//Entra na tela de cadastro de um novo destino
@RequestMapping("newDestination")
public ModelAndView setnewDestination(Model model, HttpServletRequest req){
    //Inicializa o Componente DropDown de Categoria
    List<Category> category = dashboardFacade.getCategoryList();
    List<Category> activeCategory = new ArrayList<Category>();

    //Verificação de categorias que não estão ativas
    for (Category allCAtegory : category) {
        if(allCAtegory.getCtActive() == 1){ 
            activeCategory.add(allCAtegory);
        }
    }
    model.addAttribute("categoryDropDown", activeCategory);

    return new ModelAndView("destination/newDestination", "command", new Destination());
}

Stabbing:

public List<Category> getCategoryList(){
    return categoryRepository.findAll();
}

Repository:

@Repository
public interface CategoryRepository extends BaseRepository<Category, Long>{

    List<Category> findAll();

}

Well, what happens in reality is that when I go to register a new destination and select a category the same and successfully saved at the base. But when I have re-registered a destination to my List<Category> category = dashboardFacade.getCategoryList(); comes with inconsistent object. That is, with null values.

Category object populating the Dropbox without its association having been saved:

  • [idCategory=1, ctActive=1, ctName=National, tenantId=2],
  • [idCategory=2, ctActive=0, ctName=International, tenantId=2],
  • [idCategory=3, ctActive=1, ctName=Cruising, tenantId=2],
  • [idCategory=4, ctActive=1, ctName=Spatial, tenantId=2],

I saved a new destination with the category name "National". When the dropdown simply does not appear. This is the state that Category is located in:

  • [idCategory=1, ctActive=0, ctName=null, tenantId=null],
  • [idCategory=2, ctActive=0, ctName=International, tenantId=2],
  • [idCategory=3, ctActive=1, ctName=Cruising, tenantId=2],
  • [idCategory=4, ctActive=1, ctName=Spatial, tenantId=2],

I have no idea what might be going on.

If anyone can help, I’m very grateful.

Hug to all

EDITION

Below are the mappings:

Destination.java

package br.com.joocebox.model;

import java.io.Serializable;

import javax.persistence.*;

import org.eclipse.persistence.annotations.Multitenant;
import org.eclipse.persistence.annotations.TenantDiscriminatorColumn;
import org.eclipse.persistence.config.PersistenceUnitProperties;
/**
 * The persistent class for the destination database table.
 * 
 */
@Entity
@Table(name="destination")
@Multitenant
@TenantDiscriminatorColumn(name="tenant_id", discriminatorType=DiscriminatorType.INTEGER, contextProperty=PersistenceUnitProperties.MULTITENANT_PROPERTY_DEFAULT)
@NamedQuery(name="Destination.findAll", query="SELECT d FROM Destination d")
public class Destination implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_destination")
    private Long idDestination;

    @Column(name="tenant_id", insertable=false, updatable=false)
    private Long tenantId;

    @Column(name="active")
    private byte dtActive;

    @Column(name="appear_website")
    private Boolean dtAppearWebsite;

    @Lob
    @Column(name="description")
    private String dtDescription;

    @Column(name="highlight_website")
    private Boolean dtHighlightWebsite;

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

    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_streetview")
    private StreetView streetView;

    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_video")
    private Video video;

    @OneToOne
    @JoinColumn(name="fk_category")
    private Category categories;

//  //bi-directional many-to-one association to Agency
//  @ManyToOne(fetch=FetchType.LAZY)
//  @JoinColumn(name="fk_agency")
//  private Agency agency;

    //Profiles of System. These profiles are all enum type.
    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_economic")
    private EconomicProfile economicProfiles;

    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_general")
    private GeneralProfile generalProfiles;

    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_social")
    private SocialProfile socialProfiles;

    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_trip")
    private TripProfile tripProfiles;

    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_weather")
    private WeatherProfile weatherprofile;
    //End of Profiles of System.

//  @OneToMany(mappedBy="destination")
//  private Set<Image> images;

    public Destination() {
    }

    public Long getIdDestination() {
        return this.idDestination;
    }

//Getter and Setters
}

Category.java

package br.com.joocebox.model;

import java.io.Serializable;
import java.util.Set;


import javax.persistence.*;

import org.eclipse.persistence.annotations.Multitenant;
import org.eclipse.persistence.annotations.TenantDiscriminatorColumn;
import org.eclipse.persistence.config.PersistenceUnitProperties;
/**
 * The persistent class for the category database table.
 * 
 */
@Entity
@Table(name="category")
@Multitenant
@TenantDiscriminatorColumn(name="tenant_id", discriminatorType=DiscriminatorType.INTEGER, contextProperty=PersistenceUnitProperties.MULTITENANT_PROPERTY_DEFAULT)
@NamedQuery(name="Category.findAll", query="SELECT c FROM Category c")
public class Category implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_category")
    private Long idCategory;

    @Column(name="ct_active")
    private int ctActive;

    @Column(name="ct_name")
    private String ctName;

    @Column(name="tenant_id", insertable=false, updatable=false)
    private Long tenantId;

    public Category() {
    }

    public Long getIdCategory() {
        return this.idCategory;
    }

//Getters and Setters

    @Override
    public String toString() {
        return "Category [idCategory=" + idCategory + ", ctActive=" + ctActive
                + ", ctName=" + ctName + ", tenantId=" + tenantId + "]";
    }



}

Thank you!


filipeportes,

didn’t work. I don’t really know what else can be.

I did it this way:

Category.java:

@Entity
@Table(name="category")
@Multitenant
@TenantDiscriminatorColumn(name="tenant_id", discriminatorType=DiscriminatorType.INTEGER, contextProperty=PersistenceUnitProperties.MULTITENANT_PROPERTY_DEFAULT)
@NamedQuery(name="Category.findAll", query="SELECT c FROM Category c")
public class Category implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_category")
    private Long idCategory;

    @Column(name="ct_active")
    private int ctActive;

    @Column(name="ct_name")
    private String ctName;

    @Column(name="tenant_id", insertable=false, updatable=false)
    private Long tenantId;

    //Relacionamento com Category
    @OneToMany(mappedBy="categories", fetch=FetchType.LAZY)
    private Set<Destination> destination;

    //Getters and Setters

Destination.java:

@Entity
@Table(name="destination")
@Multitenant
@TenantDiscriminatorColumn(name="tenant_id", discriminatorType=DiscriminatorType.INTEGER, contextProperty=PersistenceUnitProperties.MULTITENANT_PROPERTY_DEFAULT)
@NamedQuery(name="Destination.findAll", query="SELECT d FROM Destination d")
public class Destination implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_destination")
    private Long idDestination;

    @Column(name="tenant_id", insertable=false, updatable=false)
    private Long tenantId;

    @Column(name="active")
    private byte dtActive;

    @Column(name="appear_website")
    private Boolean dtAppearWebsite;

    @Lob
    @Column(name="description")
    private String dtDescription;

    @Column(name="highlight_website")
    private Boolean dtHighlightWebsite;

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

    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_streetview")
    private StreetView streetView;

    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_video")
    private Video video;

    @ManyToOne(cascade=CascadeType.REFRESH)
    @JoinColumn(name="fk_category")
    private Category categories;

    //Getters and Setters

It seems that something is cached, because when I give a shutdown and raise again the server my object comes consistently.

Hug

  • can add the mappings of your model classes please?

  • @filipeportes I edited the question with the current mappings. Thank you!

  • I don’t know if this is related to the problem, but I don’t see the need to use Onetoone mapping in your case, use it only if you need reverse mapping, IE, Destination within Category.

1 answer

1

this may be related to the problem, I see no need to use the mapping @OneToOne in your case, use it only if you need reverse mapping, ie Destination within Category. always prefer to use the @ManyToOne and avoid inverse mapping to the maximum.

Another good practice is to use the fetch=FetchType.LAZY, the mappings @OneToOne and @ManyToOne by default fetch EAGER, meaning it loads all the data mapped from the database even if they are not used, this can generate serious performance problems.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.