Skip to content

Instantly share code, notes, and snippets.

@carlosdelfino
Last active September 21, 2015 15:07
Show Gist options
  • Save carlosdelfino/b2297051beeef3a44d6f to your computer and use it in GitHub Desktop.
Save carlosdelfino/b2297051beeef3a44d6f to your computer and use it in GitHub Desktop.
Classes de Persistencia em cadeia, problema da persistencia de uma nova classe pai, quando as filhas já estão persistidas.
O sistema coleta dados na internet e armazena com o objeto PostData, em um determinado contexto, posteriormente um analista coleta tais dados e qualifica manualmente cada dado e assim persiste o novo processo como sendo do tipo manual usando um objeto LearningProcess, que irá conter um objeto do tipo PostDataQualification para cada PostDAta qualificado com o objeto Classification.
/**
*
*/
package com.socialsla.persistence.entity;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
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.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* @author Carlos Delfino {[email protected], Aminadabe B. Souza
* {[email protected]} e Carlos Barros {[email protected]}
*
*/
@Entity
public class LearningProcess {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
// bi-directional many-to-one association to Autor
@ManyToOne(cascade = { CascadeType.REFRESH, CascadeType.DETACH }, optional = false, fetch = FetchType.EAGER)
@JoinColumn(name = "type", referencedColumnName = "id", nullable = false, updatable = true, insertable = true)
private LearningType type;
@Temporal(TemporalType.TIMESTAMP)
Date date;
@Column(length = 250)
String shortDescription; // descrição curta do processo de treinamento
@Column(length = 500)
String description; // descrição em detalhes do processo de treinamento
/**
* Conjunto de qualificações, cada {@link PostDataQualification} faz
* referencia a um post e a qualificação dadata a ele neste processo de
* aprendizado.
*
* Uma vez que é preciso as vezes atualizar o processo de qualificação, não
* é possível cascatear o Refresh e o Merge, já que poderão haver
*
* Porém, o processo de Persistir deve ser cascateado já que assim irá
* inserir todas as qualificações já realizadas.
*
* {@link PostDataQualification} não persistido na coleção.
*/
@OneToMany(mappedBy = "learningProcess", fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST })
private Set<PostDataQualification> qualifications;
/**
* Ao usar este construtor não esqueça de definir o tipo de processo de
* aprendizado.
*
* TODO: Verificar a possibilidade de se criar uma hierarquia de classes que
* represente os tipos de processo de aprendizado, eliminando o uso da
* classe {@link LearningType}, já que o processo de aprendizado não é
* mutavel, ou seja cada processo uma vez criado não irá mudar seu tipo.
*/
public LearningProcess() {
date = new Date();
}
public LearningProcess(LearningType p_learningType) {
type = p_learningType;
date = new Date();
}
/**
* Adiciona o {@link PostDataQualification} ao processo de aprendizado
* {@link LearningType}.
*
* Não use esta função para adiconar qualificações externamente, quando
* desejar atribuir uma qualificação a um {@link PostDataQualification} use
* a função
* {@link PostDataQualification#setLearningProcess(LearningProcess)}
*
* Caso este {@link PostDataQualification} já exista, será retornado falso.
*
*
* @see Set
*
* @param p_qualification
* {@link PostDataQualification} a ser adicionado.
* @return retorna verdadeiro se foi adicionado, falso caso já exista um
* {@link PostDataQualification} igual ou o mesmo.
*/
boolean addQualification(PostDataQualification p_qualification) {
final Set<PostDataQualification> l_qualification = getQualifications();
return l_qualification.add(p_qualification);
}
public Integer getId() {
return id;
}
/**
*
* @return
*/
public Set<PostDataQualification> getQualifications() {
if (qualifications == null) {
qualifications = new HashSet<>();
}
return qualifications;
}
@Override
public String toString() {
return LearningProcess.class.getSimpleName() + ": " + type + " (" + getId() + ")";
}
}
package com.socialsla.persistence.entity;
import java.io.Serializable;
import java.lang.Integer;
import java.lang.String;
import java.util.Set;
import javax.persistence.*;
import antlr.collections.List;
/**
* Entity implementation class for Entity: LearningType
*
* @author Carlos Delfino {[email protected], Aminadabe B. Souza {[email protected]} e Carlos Barros {[email protected]}
*/
@Entity
@NamedQueries({ @NamedQuery(name = LearningType.NAMED_QUERY_FIND_ALL, query = "SELECT e FROM LearningType e"),
@NamedQuery(name = LearningType.NAMED_QUERY_FIND_BY_NAME, query = "SELECT lt FROM LearningType lt WHERE lt.name = ?") })
public class LearningType implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(length = 40, nullable = false, unique = true)
private String name;
@Column(length = 200, nullable = true, unique = false)
private String description;
@ManyToOne(fetch = FetchType.EAGER, optional = true)
@JoinColumn(name = "superType", insertable = true, nullable = true, updatable = false)
private LearningType superType;
@OneToMany(fetch = FetchType.EAGER, cascade = { CascadeType.ALL }, mappedBy = "superType")
private Set<LearningType> subTypes;
private static final long serialVersionUID = 1L;
public static final String NAMED_QUERY_FIND_ALL = "LearningType.findAll";
public static final String MANUAL_NAME = "Manual";
public static final String NAMED_QUERY_FIND_BY_NAME = "LearningType.findByName";
private LearningType() {
super();
}
public LearningType(String p_name) {
name = p_name;
}
public LearningType(String p_name, String p_desc) {
name = p_name;
description = p_desc;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public void setSuperType(LearningType p_type) {
superType = p_type;
}
@Override
public String toString() {
return getName()
+ (superType != null ? "Super: " + superType.getName() : "") + " (" + getId() + ")";
}
}
package com.socialsla.persistence.entity;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* @author Carlos Delfino {[email protected], Aminadabe B. Souza
* {[email protected]} e Carlos Barros {[email protected]}
*
*/
@Entity
@IdClass(PostDataQualificationID.class)
public class PostDataQualification {
@Id
@ManyToOne(optional = false, fetch = FetchType.EAGER)
@JoinColumn(name = "idLearningProcess", referencedColumnName = "id", insertable = true, updatable = false, nullable = false, unique = false)
private LearningProcess learningProcess;
@Id
@ManyToOne(optional = false, fetch = FetchType.EAGER, cascade = { CascadeType.MERGE })
@JoinColumn(name = "idPostData", referencedColumnName = "id", insertable = true, updatable = false, nullable = false, unique = false)
private PostData postData;
@Column(name = "pontuation", insertable = false, updatable = false, nullable = true, unique = false)
private Integer pontuation;
@Temporal(TemporalType.TIMESTAMP)
@Column(nullable = false, insertable = true, unique = false)
private final Date date;
@ManyToOne(optional = false, fetch = FetchType.EAGER)
@JoinColumn(name = "idClassification", referencedColumnName = "id", nullable = false, insertable = true, updatable = true, unique = false)
private Classification classification;
@ManyToOne(optional = false, fetch = FetchType.EAGER)
@JoinColumn(name = "idContext", referencedColumnName = "id", nullable = false, insertable = true, updatable = true, unique = false)
private Context context;
@ManyToOne(optional = true, fetch = FetchType.EAGER)
@JoinColumn(name = "idEvent", referencedColumnName = "id", nullable = true, insertable = false, updatable = false, unique = false)
private Event event;
public PostDataQualification() {
date = new Date();
}
public PostDataQualification(Context p_context, PostData p_post) {
setPostData(p_post);
context = p_context;
classification = Classification.UNKNOW;
date = new Date();
}
public PostDataQualification(LearningProcess p_learningProcess, Context p_context, PostData p_post, Event p_event) {
setLearningProcess(p_learningProcess);
context = p_context;
setPostData(p_post);
event = p_event;
classification = Classification.UNKNOW;
date = new Date();
}
public Classification getClassification() {
return classification;
}
public Context getContext() {
return context;
}
public Date getDate() {
return date;
}
public Event getEvent() {
return event;
}
public Integer getPontuation() {
return pontuation;
}
public PostData getPostData() {
return postData;
}
public void setClassification(Classification p_class) {
classification = p_class;
}
/**
* Informa a qual processo de aprendizado esta qualificação pertence.
*
* Veja que ao adicionar um processo de aprendizado, esta qualificação é
* adicionada ao conjunto de qualificações do processo.
*
* @param p_learningProcess
*/
public void setLearningProcess(LearningProcess p_learningProcess) {
learningProcess = p_learningProcess;
learningProcess.addQualification(this);
}
private void setPostData(PostData p_post) {
postData = p_post;
}
}
package com.socialsla.persistence.entity;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.ConstraintMode;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ForeignKey;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* The persistent class for the postoriginal database table.
*
* @author Carlos Delfino {[email protected], Aminadabe B. Souza
* {[email protected]} e Carlos Barros {[email protected]}
*/
@Entity
@NamedQueries({
@NamedQuery(name = PostData.NAMED_QUERY_FIND_ORIGINAL_ID, query = "SELECT pd FROM PostData pd WHERE pd.idOriginal = ?"),
@NamedQuery(name = PostData.NAMED_QUERY_FIND_SCREEN_NAME, query = "SELECT pd FROM PostData pd JOIN pd.sourceProfile sp WHERE sp.screenName = ?") })
public class PostData implements Serializable {
/**
*
*/
private static final long serialVersionUID = 7369168234620318745L;
public static final String NAMED_QUERY_FIND_ORIGINAL_ID = "PostData.findByOriginalId";
public static final String NAMED_QUERY_FIND_SCREEN_NAME = "PostData.findByScreenName";
/**
* ID no banco de dados, não confundir com o ID original do post.
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
/**
* texto integral do post
*
* Apesar de algumas redes como Twitter permitir apenas 140 caracteres,
* estou considerando o uso de outras redes qeu permitem posts bem maiores.
*/
@Column(length = 512)
private String data;
/**
* ID Original do POST conforme fornecido pela Rede Social.
*/
@Column(length = 50, nullable = false)
private String idOriginal;
// bi-directional many-to-one association to Autor
@ManyToOne(cascade = { CascadeType.REFRESH }, fetch = FetchType.EAGER)
@JoinColumn(name = "idSourceProfile", referencedColumnName = "id", nullable = false, updatable = false, insertable = true, foreignKey = @ForeignKey(ConstraintMode.PROVIDER_DEFAULT) )
private Profile sourceProfile;
// bi-directional many-to-many association to SLAContext
/**
* lista os contextos ao qual este post pertence, para cadastrar este post a
* um novo contexto, basta adicionar o post ao contexto.
*/
@ManyToMany(mappedBy = "posts", cascade = {}, fetch = FetchType.EAGER)
private Set<Context> contexts;
// bi-directional many-to-one association to Autor
@ManyToOne(cascade = {}, fetch = FetchType.EAGER)
@JoinColumn(name = "lang", referencedColumnName = "id", nullable = false, updatable = false, insertable = true, foreignKey = @ForeignKey(ConstraintMode.PROVIDER_DEFAULT) )
private Language lang = new Language("pt", "Português");
@ManyToMany(mappedBy = "posts", cascade = {}, fetch = FetchType.LAZY)
private Set<Acquisition> acquisitions;
@Temporal(TemporalType.TIMESTAMP)
@Column(nullable = true, updatable = false)
private Date createAt;
public PostData(String p_msg, String p_idOriginal, Language p_lang) {
setData(p_msg);
setIdOriginal(p_idOriginal);
setLang(p_lang);
}
public PostData() {
}
public PostData(String p_msg, String p_idOriginal) {
this(p_msg, p_idOriginal, null);
}
private void setIdOriginal(String p_idOriginal) {
idOriginal = p_idOriginal;
}
public void setIdOriginal(long p_id) {
idOriginal = String.valueOf(p_id);
}
public void setData(String p_text) {
data = p_text;
}
public void setLang(Language p_lang) {
lang = p_lang;
}
void setSourceProfile(Profile p_profile) {
sourceProfile = p_profile;
}
@Override
public String toString() {
Language lang = getLang();
String langStr = lang != null ? (" - ( " + lang.getName() + " )") : "";
return "@" + (sourceProfile != null ? sourceProfile.getScreenName() : "DESCONHECIDO") + ": " + getData()
+ langStr + " - (" + getIdOriginal() + ") (BD Id:" + getId() + ")";
}
public Integer getId() {
return id;
}
public Language getLang() {
return lang;
}
public String getData() {
return data;
}
public String getIdOriginal() {
return idOriginal;
}
public void addContext(Context p_slaContext) {
getContexts().add(p_slaContext);
}
public Set<Context> getContexts() {
if (contexts == null) {
contexts = new HashSet<>();
}
return contexts;
}
public void addAcquisition(Acquisition p_Aquisition) {
getAcquisitions().add(p_Aquisition);
p_Aquisition.addPost(this);
}
private Set<Acquisition> getAcquisitions() {
if (acquisitions == null) {
acquisitions = new HashSet<>();
}
return acquisitions;
}
public void setCreateAt(Date p_createdAt) {
createAt = p_createdAt;
}
}
package com.socialsla.persistence.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
/**
*
* @author Carlos Delfino {[email protected], Aminadabe B. Souza
* {[email protected]} e Carlos Barros {[email protected]}
*
*/
@Entity
@NamedQueries({ @NamedQuery(name = Classification.NAMED_QUERY_FIND_ALL, query = "SELECT c FROM Classification c"),
@NamedQuery(name = Classification.NAMED_QUERY_FIND_BY_NAME, query = "SELECT c FROM Classification c WHERE c.name = ?") })
public class Classification {
public static final String NAMED_QUERY_FIND_ALL = "Classification.findAll";
public static final String NAMED_QUERY_FIND_BY_NAME = "Classification.findByName";
/**
* Clasificado como desconhecido, para iniciar treinamento ou propor para
* testes
*/
public static final Classification UNKNOW = new Classification(-888, "Desconhecido");
@Id
private Integer id;
@Column(length = 50, nullable = false, unique = true)
private String name;
@Column(length = 200, nullable = true)
private String description;
public Classification() {
}
public Classification(int p_i, String p_name) {
id = p_i;
name = p_name;
}
public void setName(String p_name) {
name = p_name;
}
/**
* @return the id
*/
public Integer getId() {
return this.id;
}
/**
* @param p_id
* the id to set
*/
public void setId(Integer p_id) {
this.id = p_id;
}
/**
* @return the description
*/
public String getDescription() {
return this.description;
}
/**
* @param p_description
* the description to set
*/
public void setDescription(String p_description) {
this.description = p_description;
}
/**
* @return the name
*/
public String getName() {
return this.name;
}
@Override
public String toString() {
String l_str = getName();
l_str += " (" + getId() + ")";
return l_str;
}
}
package com.socialsla.persistence.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.ConstraintMode;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ForeignKey;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
/**
* {@link Context} é a entidade que identifica o contexto que se aplica o SLA
*
* Será com este contexto que as pesquisas serão feitas em primeiro nível,
* separando mensagens que tratem por exemplo de Links, Sites, Telefonia e
* Contrato de Serviço especifico caso sai do super contexto TIC
*
* @author Carlos Delfino {[email protected], Aminadabe B. Souza
* {[email protected]} e Carlos Barros {[email protected]}
*
*/
@Entity
@NamedQueries({ @NamedQuery(name = Context.NAMED_QUERY_FIND_ALL, query = "SELECT c FROM Context c"),
@NamedQuery(name = Context.NAMED_QUERY_FIND_NAME, query = "SELECT c FROM Context c WHERE c.name = ?") })
public class Context {
public static final String NAMED_QUERY_FIND_ALL = "Context.findAll";
public static final String NAMED_QUERY_FIND_NAME = "Context.findName";
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(length = 50, nullable = false, unique = true)
private String name;
@Column(length = 200, nullable = true)
private String description;
// bi-directional many-to-many association to SLAContext
@ManyToMany(cascade = { CascadeType.REFRESH }, fetch = FetchType.LAZY)
@JoinTable(name = "Context_of_Post", joinColumns = {
@JoinColumn(name = "idContext", referencedColumnName = "id", nullable = false, updatable = true, insertable = true, foreignKey = @ForeignKey(ConstraintMode.PROVIDER_DEFAULT) ) }, inverseJoinColumns = {
@JoinColumn(name = "idPostData", referencedColumnName = "id", nullable = false, updatable = true, insertable = true, foreignKey = @ForeignKey(ConstraintMode.PROVIDER_DEFAULT) ) })
private Set<PostData> posts;
public Context() {
}
public Context(String p_name) {
setName(p_name);
}
public void setName(String p_name) {
name = p_name;
}
public void addPost(PostData p_post) {
getPosts().add(p_post);
p_post.addContext(this);
}
private Set<PostData> getPosts() {
if (posts == null) {
posts = new HashSet<>();
}
return posts;
}
@Override
public String toString() {
return getName();
}
public String getName() {
return name;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment