Using Annotations in Java at the Class Level for Every Field - java

I have a custom annotation that I currently have annotated on every field. This is fine, but not super clean. I want to give the ability to put this annotation on the class to then automatically annotate every field.
#Target(value = {ElementType.TYPE, ElementType.FIELD})
#Retention(RetentionPolicy.RUNTIME)
public #interface TestAnnotation {
boolean searchable() default true;
String attribute() default "";
}
// Current Class
#Entity
#Table(name = "TESTER")
public class Tester () {
#Id
#GeneratedValue
#TestAnnotation
#Column(name = "ID")
private Long id;
#TestAnnotation
#Column(name = "COL_1", nullable = false)
private String col1;
#TestAnnotation
#Column(name = "COL_2", nullable = false)
private String col2;
#TestAnnotation
#Column(name = "COL_3", nullable = false, unique = true)
private String col3;
#TestAnnotation
#Column(name = "COL_4", nullable = false, unique = true)
private String col4;
}
// Expectation
#Entity
#TestAnnotation
#Table(name = "TESTER")
public class Tester () {
#Id
#GeneratedValue
#Column(name = "ID")
private Long id;
#Column(name = "COL_1", nullable = false)
private String col1;
#Column(name = "COL_2", nullable = false)
private String col2;
#Column(name = "COL_3", nullable = false, unique = true)
private String col3;
#Column(name = "COL_4", nullable = false, unique = true)
private String col4;
}

Related

How to negate several predicates

I have two entities
#Entity
#Table(name = SIGNAL")
public class TradingSignal {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID", nullable = false, unique = true)
private int id;
#Column(name = "SIGNAL_ID")
private int signalId;
#Column(name = "TICKER", length = 6)
private String ticker;
#OneToMany(cascade = CascadeType.ALL)
private Set<TsUsed> tsUsedSet;
}
and
#Entity
#Table(name = "TS_USED")
public class TsUsed {
#Id
#Column(name = "FILTER_ID", nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private int filterId;
#Column(name = "USER_ID_LSB")
private long userIdLsb;
#Column(name = "USER_ID_MSB")
private long userIdMsb;
#Column(name = "VISIBLE")
private boolean visible;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "ID", nullable = false)
private TradingSignal tradingSignal;
}
How can I find all TradingSignals where TsUsed.userIdLsb and TsUsed.userIdMsb are not exists in tsUsedSet?
Can't create valid predicate.
This code not work for me
Join<TradingSignal, TsUsed> tsUsed = getTsUsedJoin(root);
Predicate predicateUserIdLsb = builder.equal(tsUsed.get("userIdLsb"), userId.getLeastSignificantBits());
Predicate predicateUserIdMsb = builder.equal(tsUsed.get("userIdMsb"), userId.getMostSignificantBits());
Predicate predicateInvisible = builder.isFalse(tsUsed.get("visible"));
Predicate notInvisibleForUser = builder.and(predicateUserIdLsb, predicateUserIdMsb, predicateInvisible).not();

I want to know about Hibernate annotation

I have a question about "annotations" in hibernate.
I have a BaseEntity class and another class like state.java who extend
#JsonIgnoreProperties({ "hibernateLazyInitializer", "handler", "createdBy", "updatedBy" })
#MappedSuperclass
public abstract class BaseEntity<T> implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private T id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "CreatedBy", nullable = true)
private User createdBy;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "UpdatedBy", nullable = true)
private User updatedBy;
#Column(name = "createdDate", nullable = true, updatable = false)
private Date createdDate;
#Column(name = "UpdatedDate", nullable = true)
private Date updatedDate;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "subsite", nullable = true)
private Subsite subsite;
#Column(name = "ip", nullable = true)
private String ip;
#Entity
#Table(name="State")
public class State extends BaseEntity<Long> {
#Column(name = "state", nullable = true)
private String state;
#Column(name = "city", nullable = true)
private String city;
when program creat my tables in DataBase my table'design build like this:
How can I create a table so that the BaseEntity'fields place after state'fields in my Table

Saving entity using crudrepository taking too much time

I am trying to update an entry in the DB using crudrepository but its taking ~ 24 seconds for each iteration. Below is the code. Thanks in advance.
for(tmp.request.Number numb : Num_list){
EnterpriseVnumbList addNumb = entNumbdao.findByVnumbmsisdnAndEnterpriseid(numb.getNumber(), frmEntp);
if(addNumb != null){
addNumb.setEnterpriseId(toEntp); // toEnt is a class Enterprise
entNumbdao.save(addNumb); // entNumbdao is EnterpriseVnumbListRepo
addEntpToEnt++;
}else{
log.error("NumbProcessing: Failed to");
}
Here is my EnterpriseVnumbList class
#Entity
#Table(name = "enterprise_vnumb_list", uniqueConstraints = {
#UniqueConstraint(columnNames = {"vnumb_msisdn"})})
#XmlRootElement
public class EnterpriseVnumbList implements Serializable {
#Size(max = 10)
#Column(name = "parent_id")
private String parentId;
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id", nullable = false)
private Long id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 30)
#Column(name = "vnumb_msisdn", nullable = false, length = 30)
private String vnumbmsisdn;
#Size(max = 30)
#Column(name = "imsi", length = 30)
private String imsi;
#Column(name = "assigned")
private Boolean assigned;
#Size(max = 30)
#Column(name = "assigned_to_sim", length = 30)
private String assignedtosim;
#JoinColumn(name = "enterprise_id", referencedColumnName = "enterprise_id", nullable = false)
#ManyToOne(optional = false)
private Enterprise enterpriseid;
/// Some code here
}
// Here is EnterpriseVnumbListRepo class
#RepositoryDefinition(domainClass=EnterpriseVnumbList.class, idClass=Integer.class)
public interface EnterpriseVnumbListRepo extends CrudRepository<EnterpriseVnumbList, Integer>, JpaSpecificationExecutor<EnterpriseVnumbList>{
EnterpriseVnumbList findByVnumbmsisdnAndEnterpriseidAndAssigned(String vsim, Enterprise enterpriseid, boolean assgn);
EnterpriseVnumbList findByVnumbmsisdnAndEnterpriseid(String vsim, Enterprise enterpriseid);
List<EnterpriseVnumbList> findByEnterpriseidAndAssigned(Enterprise entp, boolean assgn);
EnterpriseVnumbList findByVnumbmsisdnAndAssignedtosim(String vsim, String sim);
EnterpriseVnumbList findByVnumbmsisdnAndEnterpriseidAndAssignedNot(String vsim, Enterprise enterpriseid, boolean assgn);
Long countByEnterpriseidAndAssigned(Enterprise entp, boolean assgn);
Long countByEnterpriseid(Enterprise entp);
}

JPA - Issues removing child entities on bidirectional mapping

I need to remove a child entity called "SystemParamater" based on the it´s id.
What i was trying to do:
- Begin Tran
SystemParameter param EntityManager.find(SystemParameter.class,<paremeter.id>)
EntityManager.remove(param)
-Commit tran
But the entity was not removed.
What´s the correct way to remove a child entity?
Below, you could find my entities:
SystemParameter:
#Entity
#Table(name = "system_parameters")
#Cacheab le
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class SystemParameter extends BasicEntity {
private static final long serialVersionUID = -6416605270912358340L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "paramName", length = 50, nullable = false)
private String paramName;
#Column(name = "paramValue", length = 255, nullable = false)
private String paramValue;
#Column(name = "encrypted", nullable = false)
#Type(type = "yes_no")
private Boolean encrypted = Boolean.FALSE;
#ManyToOne
#JoinColumn(name = "groupId", nullable = false)
private SystemParameterGroup parameterGroup;
}
SystemParameterGroup:
#Entity
#Table(name = "system_parameter_groups", uniqueConstraints = { #UniqueConstraint(columnNames = { "searchKey" }) })
#Cacheable
public class SystemParameterGroup extends BasicEntity {
private static final long serialVersionUID = -1762633144642103487L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name", length = 50, nullable = false)
private String name;
/**
* Description.
*/
#Column(name = "description", length = 255, nullable = false)
private String description;
/**
* Search key.
*/
#Column(name = "searchKey", length = 50, nullable = false)
private String searchKey;
/**
* System parameter list.
*/
#OneToMany(fetch = FetchType.EAGER, mappedBy = "parameterGroup", cascade = CascadeType.ALL, orphanRemoval = true)
#OrderBy("paramName")
private List<SystemParameter> systemParameterList;
}
You have to remove the SystemParameter entity also from the SystemParameterGroup's list of SystemParameter:
systemParameterGroup.getSystemParameterList().remove(systemParameter);
This issue is related to this one.

ORA-01400 cannot insert null error in one to one relationship

i have this code
public void guardarAspirante(AspiranteDTO aspiranteDTO) {
Aspirante aspirante = new Aspirante();
String usuarioMovimiento = AspiranteCN.class.getSimpleName();
Date fecha = new Date();
aspirante.setCodigoAlumno(aspiranteDTO.getCodigoUniversitario());
aspirante.setNombre(aspiranteDTO.getNombre());
aspirante.setApellidoPaterno(aspiranteDTO.getPrimerApellido());
aspirante.setApellidoMaterno(aspiranteDTO.getSegundoApellido());
aspirante.setUsuarioMovimiento(usuarioMovimiento);
aspirante.setFechaMovimiento(fecha);
Solicitud solicitud = new Solicitud(aspirante.getSolicitudId());
solicitud.setAspirante(aspirante);
solicitud.setSolicitudId(aspirante.getSolicitudId());
solicitud.setOfertaId(aspiranteDTO.getOfertaAcademica());
solicitud.setPeriodoId(aspiranteDTO.getPeriodo());
solicitud.setAportacion(aspiranteDTO.getAportacionVoluntaria());
solicitud.setFechaMovimiento(fecha);
solicitud.setUsuarioMovimiento(usuarioMovimiento);
aspirante.setSolicitud(solicitud);
....
aspiranteDAO.persist(aspirante);
}
and this error
Internal Exception: java.sql.SQLException: ORA-01400: cannot insert NULL into ("RPINGRE"."ARE_SOLI"."ARE_SOLI_SOLIASPI_ID")
This is Aspirante Entity (Fragment)
#Entity
#Table(name = "ARE_SOLIASPI", catalog = "", schema = "RPINGRE")
public class Aspirante implements Serializable {
private static final long serialVersionUID = 1L;
#SequenceGenerator(sequenceName = "RPINGRE.SQ_ARE_SOLIASPI",
name = "RPINGRE.SQ_ARE_SOLIASPI",
initialValue = 1,
allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "RPINGRE.SQ_ARE_SOLIASPI")
#Id
#Basic(optional = false)
#Column(name = "ARE_SOLIASPI_ID")
private Long solicitudId;
#Basic(optional = false)
#Column(name = "ARE_SOLIASPI_CODIGO")
private String codigoAlumno;
#Basic(optional = false)
#Column(name = "ARE_SOLIASPI_NOMBRE")
private String nombre;
#Column(name = "ARE_SOLIASPI_APE_PATERNO")
private String apellidoPaterno;
#Column(name = "ARE_SOLIASPI_APE_MATERNO")
private String apellidoMaterno;
#Basic(optional = false)
#Column(name = "ARE_SOLIASPI_MOV_USUARIO")
private String usuarioMovimiento;
#Basic(optional = false)
#Column(name = "ARE_SOLIASPI_MOV_FECHA")
#Temporal(TemporalType.TIMESTAMP)
private Date fechaMovimiento;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "aspirante", fetch = FetchType.LAZY)
private Solicitud solicitud;
and Solicitud Entity (Fragment)
#Entity
#Table(name = "ARE_SOLI", catalog = "", schema = "RPINGRE")
public class Solicitud implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "ARE_SOLI_SOLIASPI_ID")
private Long solicitudId;
#Basic(optional = false)
#Column(name = "ARE_SOLI_MOV_USUARIO")
private String usuarioMovimiento;
#Basic(optional = false)
#Column(name = "ARE_SOLI_MOV_FECHA")
#Temporal(TemporalType.TIMESTAMP)
private Date fechaMovimiento;
#Column(name = "ARE_SOLI_PERIODO_ID")
private String periodoId;
#Column(name = "ARE_SOLI_OFERTA_ID")
private Long ofertaId;
#Column(name = "ARE_SOLI_APORTACION")
private Long aportacion;
#JoinColumn(name = "ARE_SOLI_SOLIASPI_ID", referencedColumnName = "ARE_SOLIASPI_ID", insertable = false, updatable = false, nullable = false)
#OneToOne(optional = false, fetch = FetchType.LAZY)
private Aspirante aspirante;
.....
}
try changing GenerationType.SEQUENCE to GenerationType.Auto.
The ORA-01400 error says that you are trying to insert a NULL into a column defined as NOT NULL.
I suggest you ether set a default value on the column or have your code make sure the NOT NULL columns have data before you do the INSERT (or use an NVL function in your INSERT statement)

Categories

Resources