Neodatis and duplicities - java

Neodatis create a new "Pais" when there is an equal one.
I'm working with Neodatis on a GUI. I have a database that contains "Jugadores" and "Pais." The "Jugadores" have an attribute of "Pais". When I want to add a new "Jugadores" to the database with one of the existing "Pais", recreate it in the database, since the query does not return that there is one with the same name.
GUI code:
gestionLiga gestionLiga = new gestionLiga();
gestionLiga.altaJugador(txtNombre.getText(), txtDeporte.getText(), txtCiudad.getText(), Integer.parseInt(txtEdad.getText()), gestionLiga.sacarPais(txtPais.getText()));
gestionLiga.sacarPais code:
public Pais sacarPais(String pais)
{
odb = ODBFactory.open("EQUIPOS.test");
IQuery query = new CriteriaQuery(Pais.class, Where.equal("nombre",pais));
Objects <Pais> listado = odb.getObjects(query);
if(listado.size() == 0)
{
int contador;
IQuery query2 = new CriteriaQuery(Pais.class);
Objects <Pais> listado2 = odb.getObjects(query2);
contador = listado2.size()+1;
odb.close();
return new Pais(contador, pais);
}
else
{
odb.close();
return (Pais)listado.getFirst();
}
}
gestionLiga.altaJugador code:
public void altaJugador(String nombre, String deporte, String ciudad, int edad, Pais pais)
{
odb = ODBFactory.open("EQUIPOS.test");
Jugadores jugador = new Jugadores(nombre, deporte, ciudad, edad, pais);
odb.store(jugador);
odb.close();
}
Pais class code:
class Pais
{
private int id;
private String nombre;
public Pais(){}
public Pais(int id, String nombre) {
this.id = id;
this.nombre = nombre;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String toString()
{
return this.nombre;
}
}
Jugadores class code:
public class Jugadores
{
private String nombre, deporte, ciudad;
private int edad;
private Pais pais;
public Jugadores(){}
public Jugadores(String nombre, String deporte, String ciudad, int edad, Pais pais)
{
this.nombre = nombre;
this.deporte = deporte;
this.ciudad = ciudad;
this.edad = edad;
this.pais = pais;
}
public String getNombre()
{
return nombre;
}
public void setNombre(String nombre)
{
this.nombre = nombre;
}
public String getDeporte()
{
return deporte;
}
public void setDeporte(String deporte)
{
this.deporte = deporte;
}
public String getCiudad()
{
return ciudad;
}
public void setCiudad(String ciudad)
{
this.ciudad = ciudad;
}
public int getEdad()
{
return edad;
}
public void setEdad(int edad)
{
this.edad = edad;
}
public Pais getPais() {
return pais;
}
public void setPais(Pais pais) {
this.pais = pais;
}
#Override
public String toString() {
return "NOMBRE: " + nombre + " - DEPORTE: " + deporte + " - CIUDAD: " + ciudad + " - EDAD: " + edad + " - PAIS: " + pais;
}
}
If I enter two players with the same country, the query in theory should return me that there is already a Pais with that name, which should not create a new one, however, enter the IF and create a new one.
Thanks for the help!

I just don't close odb on sacarPais, then I don't open (because I can't open it twice)on altaJugador. After insert a new Jugador with Pais reference, I close the odb. It's done, a bu*****t.

Related

My List<Object> is not being passed correctly as object of my ModelAndView

In my Spring Controller I have:
List<User> Users = this.userService.UsersList();
mav = new ModelAndView("users");
mav.addObject("Users", Users);
When I iterate over Users I can see all the attributes values of every element of my list.
This is my .jsp code:
<c:forEach items="${Users}" var="usr">
${usr}
</c:forEach>
This is my users class:
#Entity
#Table(name="usuario")
public class User implements Serializable {
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#JoinColumn(name = "id_perfil")
#OneToOne(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
private Perfil perfil;
#Column(name="nombre")
private String nombre;
#Column(name="usuario")
private String usuario;
#Column(name="contrasenia")
private String contrasenia;
#Column(name="correo")
private String correo;
#Column(name="telefono")
private String telefono;
#Column(name="imagen_perfil")
private String imagen_perfil;
#Column(name="intento_fallido")
private int intento_fallido;
#Column(name="intranet_id")
private Integer intranet_id;
#Column(name="intranet_notaria")
private Integer intranet_notaria;
#Column(name="intranet_token_codigo")
private String intranet_token_codigo;
#Column(name="intranet_token_fecha")
#Temporal(TemporalType.TIMESTAMP)
private Date intranet_token_fecha;
#Column(name="tesoreria_token_codigo")
private String tesoreria_token_codigo;
#Column(name="tesoreria_token_fecha")
#Temporal(TemporalType.TIMESTAMP)
private Date tesoreria_token_fecha;
#Column(name="activo")
private int activo;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public Perfil getPerfil() { return perfil; }
public void setPerfil(Perfil perfil) { this.perfil = perfil; }
public String getNombre() { return nombre; }
public void setNombre(String nombre) { this.nombre = nombre; }
public String getUsuario() { return usuario; }
public void setUsuario(String usuario) { this.usuario = usuario; }
public String getContrasenia() { return contrasenia; }
public void setContrasenia(String contrasenia) { this.contrasenia = contrasenia; }
public String getCorreo() { return correo; }
public void setCorreo(String correo) { this.correo = correo; }
public String getTelefono() { return telefono; }
public void setTelefono(String telefono) { this.telefono = telefono; }
public String getImagenPerfil() { return imagen_perfil; }
public void setImagenPerfil(String imagen_perfil) { this.imagen_perfil = imagen_perfil; }
public int getIntentoFallido() { return intento_fallido; }
public void setIntentoFallido(int intento_fallido) { this.intento_fallido = intento_fallido; }
public Integer getIntranetId() { return intranet_id; }
public void setIntranetId(Integer intranet_id) { this.intranet_id = intranet_id; }
public Integer getIntranetNotaria() { return intranet_notaria; }
public void setIntranetNotaria(Integer intranet_notaria) { this.intranet_notaria = intranet_notaria; }
public String getIntranetTokenCodigo() { return intranet_token_codigo; }
public void setIntranetTokenCodigo(String intranet_token_codigo) { this.intranet_token_codigo = intranet_token_codigo; }
public Date getIntranetTokenFecha() { return intranet_token_fecha; }
public void setIntranetTokenFecha(Date intranet_token_fecha) { this.intranet_token_fecha = intranet_token_fecha; }
public String getTesoreriaTokenCodigo() { return tesoreria_token_codigo; }
public void setTesoreriaTokenCodigo(String tesoreria_token_codigo) { this.tesoreria_token_codigo = tesoreria_token_codigo; }
public Date getTesoreriaTokenFecha() { return tesoreria_token_fecha; }
public void setTesoreriaTokenFecha(Date tesoreria_token_fecha) { this.tesoreria_token_fecha = tesoreria_token_fecha; }
public int getActivo() { return activo; }
public void setActivo(int activo) { this.activo = activo; }
#Override
public String toString() {
return "Id:" + id + ", " + "Perfil:" + perfil.getNombre() + ", " + "Id_Perfil:" + perfil.getId() + ", " + "Nombre:" + nombre + ", " + "Usuario:" + usuario + ", " + "Correo:" + correo + ", " + "Teléfono:" + telefono + ", " + "Image_Perfil:" + imagen_perfil + ", " + "Intranet_Id:" + intranet_id + ", " + "Intranet_Notaria:" + intranet_notaria + ", " + "Activo:" + activo;
}
}
The problem is that ${usr} is only displaying some of my attributes, but not all! I need to display all the attributes in my jsp.
Try using camelCase notation if you are not doing so. For example instead of ${usr.imagen_perfil} use ${usr.imagenPerfil}. I think it will be expecting to use the object getters getImagenPerfil().

JPA 2.2: Using find method to retrieve data from mysqlDB

I´m using JPA 2.2(Openjpa) running on OpenLiberty and mysqlVer 15.1 Distrib 10.1.21-MariaDB.
I have an object call Account where I use the entityManager.find to retrieve a given record.
The record is indeed retrieved but only this column "status" returns null.
But when I do the manual select against the DB,the value is there.
My Entity class
Account
package br.com.rsm.model;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
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.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Transient;
//#XmlRootElement
#Entity
#Table(name = "tb_account")
#NamedQueries({
#NamedQuery(name="Account.findByEmail", query="SELECT a FROM Account a where a.email = :email"),
#NamedQuery(name="Account.findByCpf", query="SELECT a FROM Account a where a.cpf = :cpf"),
#NamedQuery(name="Account.findByUserId", query="SELECT a FROM Account a where a.userId = :userId")
})
public class Account implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String userId;
private String fullname;
private String email;
private String birthdate;
private String cpf;
private String rg;
private String address;
private String addressNumber;
private String complement;
private String cep;
private String state;
private int city;
private String phone;
private String mobile;
private String carrier;
#Column(name = "status")
private String status;
private long leftSide;
private long rightSide;
private Timestamp created;
private String parentId;
private String parentSide;
private String networkSide;
private Timestamp activated;
private double points;
private String nickname;
private String nis;
private String whatsapp;
private long bank;
private String accountType;
private String branchNumber;
private String branchDigit;
private String accountNumber;
private String accountDigit;
private String accountOwner;
private String cpfAccountOwner;
private String facebookID;
private double career;
private double pb;
private int certID;
private String automaticRenovation;
private String emailPagamento;
#Transient
private Account rightSideAccount;
#Transient
private Account leftSideAccount;
#Transient
private boolean searchableBySignedInUser;
#Transient
private long totalCandidatosAgente;
#Transient
private long totalAgentes;
#Transient
private long totalAgentesBracoEsq;
#Transient
private long totalAgentesBracoDir;
#Transient
private long totalAnjos;
#Transient
private boolean cfaCompleto;
//#Transient
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#JoinColumn(name = "owner" )
List<Ticket> tickets = new ArrayList<Ticket>();
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#OrderBy("created DESC")
#JoinColumn(name = "accountId" )
private List<Score> scores = new ArrayList<Score>();
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#OrderBy("activated DESC")
#JoinColumn(name = "idAccount" )
private List<ProductAccount> productsAccount = new ArrayList<ProductAccount>();
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#JoinColumn(name = "origin" )
private List<Trade> trades = new ArrayList<Trade>();
/**
* Construtor
*/
public Account() {}
public List<Trade> getTrades() {
return trades;
}
public void setTrades(List<Trade> trades) {
this.trades = trades;
}
public List<ProductAccount> getProductsAccount() {
return productsAccount;
}
public void setProductsAccount(List<ProductAccount> productsAccount) {
this.productsAccount = productsAccount;
}
public List<Score> getScores() {
return scores;
}
public void setScores(List<Score> scores) {
this.scores = scores;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getRg() {
return rg;
}
public void setRg(String rg) {
this.rg = rg;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAddressNumber() {
return addressNumber;
}
public void setAddressNumber(String addressNumber) {
this.addressNumber = addressNumber;
}
public String getComplement() {
return complement;
}
public void setComplement(String complement) {
this.complement = complement;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getCity() {
return city;
}
public void setCity(int city) {
this.city = city;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getCarrier() {
return carrier;
}
public void setCarrier(String carrier) {
this.carrier = carrier;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public long getLeftSide() {
return leftSide;
}
public void setLeftSide(long leftSide) {
this.leftSide = leftSide;
}
public long getRightSide() {
return rightSide;
}
public void setRightSide(long rightSide) {
this.rightSide = rightSide;
}
public Timestamp getCreated() {
return created;
}
public void setCreated(Timestamp created) {
this.created = created;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getParentSide() {
return parentSide;
}
public void setParentSide(String parentSide) {
this.parentSide = parentSide;
}
public String getNetworkSide() {
return networkSide;
}
public void setNetworkSide(String networkSide) {
this.networkSide = networkSide;
}
public List<Ticket> getTickets() {
return tickets;
}
public void setTickets(List<Ticket> tickets) {
this.tickets = tickets;
}
public Timestamp getActivated() {
return activated;
}
public void setActivated(Timestamp activated) {
this.activated = activated;
}
public double getPoints() {
return points;
}
public void setPoints(double points) {
this.points = points;
}
#Transient
public String getShortName() {
if(fullname==null){
return "";
}
if (nickname == null || nickname.isEmpty() ) {
nickname = fullname;
}
if(nickname != null || !nickname.isEmpty()){
String[] arrTmp = fullname.replace("\n", " ").split(" ");
String shortName = "";
if(arrTmp.length >= 2){
shortName = arrTmp[0] + " " + arrTmp[1] ;
}else if(arrTmp.length >= 1){
shortName = arrTmp[0];
}
//Passo o limitador de tamanho para ambas situações.
if(shortName!=null){
if(shortName.length() > 20){
shortName = fullname.substring(0, 19) + "...";
}
}
return shortName;
}
return "";
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getNis() {
return nis;
}
public void setNis(String nis) {
this.nis = nis;
}
public String getWhatsapp() {
return whatsapp;
}
public void setWhatsapp(String whatsapp) {
this.whatsapp = whatsapp;
}
public long getBank() {
return bank;
}
public void setBank(long bank) {
this.bank = bank;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType;
}
public String getBranchNumber() {
return branchNumber;
}
public void setBranchNumber(String branchNumber) {
this.branchNumber = branchNumber;
}
public String getBranchDigit() {
return branchDigit;
}
public void setBranchDigit(String branchDigit) {
this.branchDigit = branchDigit;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getAccountDigit() {
return accountDigit;
}
public void setAccountDigit(String accountDigit) {
this.accountDigit = accountDigit;
}
public String getAccountOwner() {
return accountOwner;
}
public void setAccountOwner(String accountOwner) {
this.accountOwner = accountOwner;
}
public String getCpfAccountOwner() {
return cpfAccountOwner;
}
public void setCpfAccountOwner(String cpfAccountOwner) {
this.cpfAccountOwner = cpfAccountOwner;
}
public String getFacebookID() {
return facebookID;
}
public void setFacebookID(String facebookID) {
this.facebookID = facebookID;
}
public double getCareer() {
return career;
}
public void setCareer(double career) {
this.career = career;
}
public double getPb() {
return pb;
}
public void setPb(double pb) {
this.pb = pb;
}
public int getCertID() {
return certID;
}
public void setCertID(int certID) {
this.certID = certID;
}
public String getAutomaticRenovation() {
return automaticRenovation;
}
public void setAutomaticRenovation(String automaticRenovation) {
this.automaticRenovation = automaticRenovation;
}
public String getEmailPagamento() {
return emailPagamento;
}
public void setEmailPagamento(String emailPagamento) {
this.emailPagamento = emailPagamento;
}
public Account getRightSideAccount() {
return rightSideAccount;
}
public void setRightSideAccount(Account rightSideAccount) {
this.rightSideAccount = rightSideAccount;
}
public Account getLeftSideAccount() {
return leftSideAccount;
}
public void setLeftSideAccount(Account leftSideAccount) {
this.leftSideAccount = leftSideAccount;
}
public boolean isSearchableBySignedInUser() {
return searchableBySignedInUser;
}
public void setSearchableBySignedInUser(boolean searchableBySignedInUser) {
this.searchableBySignedInUser = searchableBySignedInUser;
}
public long getTotalCandidatosAgente() {
return totalCandidatosAgente;
}
public void setTotalCandidatosAgente(long totalCandidatosAgente) {
this.totalCandidatosAgente = totalCandidatosAgente;
}
public long getTotalAgentes() {
return totalAgentes;
}
public void setTotalAgentes(long totalAgentes) {
this.totalAgentes = totalAgentes;
}
public long getTotalAgentesBracoEsq() {
return totalAgentesBracoEsq;
}
public void setTotalAgentesBracoEsq(long totalAgentesBracoEsq) {
this.totalAgentesBracoEsq = totalAgentesBracoEsq;
}
public long getTotalAgentesBracoDir() {
return totalAgentesBracoDir;
}
public void setTotalAgentesBracoDir(long totalAgentesBracoDir) {
this.totalAgentesBracoDir = totalAgentesBracoDir;
}
public long getTotalAnjos() {
return totalAnjos;
}
public void setTotalAnjos(long totalAnjos) {
this.totalAnjos = totalAnjos;
}
public boolean isCfaCompleto() {
return cfaCompleto;
}
public void setCfaCompleto(boolean cfaCompleto) {
this.cfaCompleto = cfaCompleto;
}
/**
* Adiciona uma nova classe Score
* #param score Score
*/
public void addScore(Score score) {
getScores().add(score);
}
public void addProductAccount(ProductAccount productAccount) {
getProductsAccount().add(productAccount);
}
public void addTrade(Trade trade) {
getTrades().add(trade);
}
#Override
public String toString() {
return "Account [id=" + id + ", userId=" + userId + ", fullname=" + fullname + ", email=" + email
+ ", birthdate=" + birthdate + ", cpf=" + cpf + ", rg=" + rg + ", address=" + address
+ ", addressNumber=" + addressNumber + ", complement=" + complement + ", cep=" + cep + ", state="
+ state + ", city=" + city + ", phone=" + phone + ", mobile=" + mobile + ", carrier=" + carrier
+ ", status=" + status + ", leftSide=" + leftSide + ", rightSide=" + rightSide + ", created=" + created
+ ", parentId=" + parentId + ", parentSide=" + parentSide + ", networkSide=" + networkSide
+ ", activated=" + activated + ", points=" + points + ", nickname=" + nickname + ", nis=" + nis
+ ", whatsapp=" + whatsapp + ", bank=" + bank + ", accountType=" + accountType + ", branchNumber="
+ branchNumber + ", branchDigit=" + branchDigit + ", accountNumber=" + accountNumber + ", accountDigit="
+ accountDigit + ", accountOwner=" + accountOwner + ", cpfAccountOwner=" + cpfAccountOwner
+ ", facebookID=" + facebookID + ", career=" + career + ", pb=" + pb + ", certID=" + certID
+ ", automaticRenovation=" + automaticRenovation + ", emailPagamento=" + emailPagamento
+ ", rightSideAccount=" + rightSideAccount + ", leftSideAccount=" + leftSideAccount
+ ", searchableBySignedInUser=" + searchableBySignedInUser + ", totalCandidatosAgente="
+ totalCandidatosAgente + ", totalAgentes=" + totalAgentes + ", totalAgentesBracoEsq="
+ totalAgentesBracoEsq + ", totalAgentesBracoDir=" + totalAgentesBracoDir + ", totalAnjos=" + totalAnjos
+ ", cfaCompleto=" + cfaCompleto + ", tickets=" + tickets + ", scores=" + scores + ", productsAccount="
+ productsAccount + ", trades=" + trades + "]";
}
}
And this is my select result( snapshot table is to big )
[
id=2111,
userId=99YWK,
fullname=PatrickRibeiroBraz,
email=null,
birthdate=null,
cpf=null,
rg=null,
address=null,
addressNumber=null,
complement=null,
cep=null,
state=null,
city=0,
phone=null,
mobile=null,
carrier=null,
status=null,
leftSide=0,
rightSide=0,
created=2018-06-1212: 09: 29.0,
parentId=999I2,
parentSide=null,
networkSide=null,
activated=null,
points=0.0,
nickname=null,
nis=null,
whatsapp=null,
bank=0,
accountType=null,
branchNumber=null,
branchDigit=null,
accountNumber=null,
accountDigit=null,
accountOwner=null,
cpfAccountOwner=null,
facebookID=null,
career=0.0,
pb=0.0,
certID=0,
automaticRenovation=null,
emailPagamento=null,
rightSideAccount=null,
leftSideAccount=null,
searchableBySignedInUser=false,
totalCandidatosAgente=0,
totalAgentes=0,
totalAgentesBracoEsq=0,
totalAgentesBracoDir=0,
totalAnjos=0,
cfaCompleto=false,
tickets={
IndirectList: notinstantiated
},
scores={
IndirectList: notinstantiated
},
productsAccount={
IndirectList: notinstantiated
},
trades={
IndirectList: notinstantiated
}
]
ID fullname status
2111 Patrick Ribeiro Braz C
Has anyone went through this before?

Null Pointer at foreign key

I'm using MySQL and Hibernate. I've added record to Receiving table and have id and barcode fields as foreign keys in transaction table rcid and barcode.
When I search a specific record using id:
int id =(Integer)defaultTableModel.getValueAt(jReceivingsTable.getSelectedRow(),0);
Receivings receivings = manager.searchReceivingsId(id);
that doesn't null, printing id return appropriate value so why I'm getting null when I set it to Transaction table?
Rctransaction rctransaction = new Rctransaction();
rctransaction.getReceivings().getId().setId(id); // here id has value
rctransaction.getReceivings().getId().setBarcode(barcode);
rctransaction.setReceivings(receivings);
Here are classes :
Receivings.java
public class Receivings implements java.io.Serializable {
private ReceivingsId id;
private Suppliers suppliers;
private String itemName;
private String category;
private double wholesalePrice;
private double retailPrice;
private long tax1;
private long tax2;
private String type1;
private String type2;
private int quantityStock;
private int receivingQuantity;
private int recorderLevel;
private String receivingDate;
private double discount;
private Set itemses = new HashSet(0);
private Set rctransactions = new HashSet(0);
public Receivings() {
}
public Receivings(ReceivingsId id, Suppliers suppliers, String itemName, String category, double wholesalePrice, double retailPrice, long tax1, long tax2, String type1, String type2, int quantityStock, int receivingQuantity, int recorderLevel, String receivingDate, double discount) {
this.id = id;
this.suppliers = suppliers;
this.itemName = itemName;
this.category = category;
this.wholesalePrice = wholesalePrice;
this.retailPrice = retailPrice;
this.tax1 = tax1;
this.tax2 = tax2;
this.type1 = type1;
this.type2 = type2;
this.quantityStock = quantityStock;
this.receivingQuantity = receivingQuantity;
this.recorderLevel = recorderLevel;
this.receivingDate = receivingDate;
this.discount = discount;
}
public Receivings(ReceivingsId id, Suppliers suppliers, String itemName, String category, double wholesalePrice, double retailPrice, long tax1, long tax2, String type1, String type2, int quantityStock, int receivingQuantity, int recorderLevel, String receivingDate, double discount, Set itemses, Set rctransactions) {
this.id = id;
this.suppliers = suppliers;
this.itemName = itemName;
this.category = category;
this.wholesalePrice = wholesalePrice;
this.retailPrice = retailPrice;
this.tax1 = tax1;
this.tax2 = tax2;
this.type1 = type1;
this.type2 = type2;
this.quantityStock = quantityStock;
this.receivingQuantity = receivingQuantity;
this.recorderLevel = recorderLevel;
this.receivingDate = receivingDate;
this.discount = discount;
this.itemses = itemses;
this.rctransactions = rctransactions;
}
public ReceivingsId getId() {
return this.id;
}
public void setId(ReceivingsId id) {
this.id = id;
}
public Suppliers getSuppliers() {
return this.suppliers;
}
public void setSuppliers(Suppliers suppliers) {
this.suppliers = suppliers;
}
public String getItemName() {
return this.itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getCategory() {
return this.category;
}
public void setCategory(String category) {
this.category = category;
}
public double getWholesalePrice() {
return this.wholesalePrice;
}
public void setWholesalePrice(double wholesalePrice) {
this.wholesalePrice = wholesalePrice;
}
public double getRetailPrice() {
return this.retailPrice;
}
public void setRetailPrice(double retailPrice) {
this.retailPrice = retailPrice;
}
public long getTax1() {
return this.tax1;
}
public void setTax1(long tax1) {
this.tax1 = tax1;
}
public long getTax2() {
return this.tax2;
}
public void setTax2(long tax2) {
this.tax2 = tax2;
}
public String getType1() {
return this.type1;
}
public void setType1(String type1) {
this.type1 = type1;
}
public String getType2() {
return this.type2;
}
public void setType2(String type2) {
this.type2 = type2;
}
public int getQuantityStock() {
return this.quantityStock;
}
public void setQuantityStock(int quantityStock) {
this.quantityStock = quantityStock;
}
public int getReceivingQuantity() {
return this.receivingQuantity;
}
public void setReceivingQuantity(int receivingQuantity) {
this.receivingQuantity = receivingQuantity;
}
public int getRecorderLevel() {
return this.recorderLevel;
}
public void setRecorderLevel(int recorderLevel) {
this.recorderLevel = recorderLevel;
}
public String getReceivingDate() {
return this.receivingDate;
}
public void setReceivingDate(String receivingDate) {
this.receivingDate = receivingDate;
}
public double getDiscount() {
return this.discount;
}
public void setDiscount(double discount) {
this.discount = discount;
}
public Set getItemses() {
return this.itemses;
}
public void setItemses(Set itemses) {
this.itemses = itemses;
}
public Set getRctransactions() {
return this.rctransactions;
}
public void setRctransactions(Set rctransactions) {
this.rctransactions = rctransactions;
}
}
ReceivingsId.java
//Composition of Id and Barcode of Receivings
public class ReceivingsId implements java.io.Serializable {
private int id;
private int barcode;
public ReceivingsId() {
}
public ReceivingsId(int id, int barcode) {
this.id = id;
this.barcode = barcode;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public int getBarcode() {
return this.barcode;
}
public void setBarcode(int barcode) {
this.barcode = barcode;
}
public boolean equals(Object other) {
if ( (this == other ) ) return true;
if ( (other == null ) ) return false;
if ( !(other instanceof ReceivingsId) ) return false;
ReceivingsId castOther = ( ReceivingsId ) other;
return (this.getId()==castOther.getId())
&& (this.getBarcode()==castOther.getBarcode());
}
public int hashCode() {
int result = 17;
result = 37 * result + this.getId();
result = 37 * result + this.getBarcode();
return result;
}
}
Rctransaction.java
public class Rctransaction implements java.io.Serializable {
private Integer id;
private Receivings receivings;
private String transaction;
private String supplierName;
private String itemName;
private double quantity;
private String paymentType;
private double amountTendred;
private double due;
private double total;
private double price;
private int recorderLevel;
public Rctransaction() {
}
public Rctransaction(Receivings receivings, String transaction, String supplierName, String itemName, double quantity, String paymentType, double amountTendred, double due, double total, double price, int recorderLevel) {
this.receivings = receivings;
this.transaction = transaction;
this.supplierName = supplierName;
this.itemName = itemName;
this.quantity = quantity;
this.paymentType = paymentType;
this.amountTendred = amountTendred;
this.due = due;
this.total = total;
this.price = price;
this.recorderLevel = recorderLevel;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Receivings getReceivings() {
return this.receivings;
}
public void setReceivings(Receivings receivings) {
this.receivings = receivings;
}
public String getTransaction() {
return this.transaction;
}
public void setTransaction(String transaction) {
this.transaction = transaction;
}
public String getSupplierName() {
return this.supplierName;
}
public void setSupplierName(String supplierName) {
this.supplierName = supplierName;
}
public String getItemName() {
return this.itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public double getQuantity() {
return this.quantity;
}
public void setQuantity(double quantity) {
this.quantity = quantity;
}
public String getPaymentType() {
return this.paymentType;
}
public void setPaymentType(String paymentType) {
this.paymentType = paymentType;
}
public double getAmountTendred() {
return this.amountTendred;
}
public void setAmountTendred(double amountTendred) {
this.amountTendred = amountTendred;
}
public double getDue() {
return this.due;
}
public void setDue(double due) {
this.due = due;
}
public double getTotal() {
return this.total;
}
public void setTotal(double total) {
this.total = total;
}
public double getPrice() {
return this.price;
}
public void setPrice(double price) {
this.price = price;
}
public int getRecorderLevel() {
return this.recorderLevel;
}
public void setRecorderLevel(int recorderLevel) {
this.recorderLevel = recorderLevel;
}
}
You are instantiating the Hibernate objects in the wrong order.
First you need a ReceivingsId :
ReceivingsId rid = new ReceivingsId (id, barcode);
Then add this rid to a Receivings:
Receivings rec = new Receivings();
rec.setId(rid);
And finally set it to the Rctransaction:
Rctransaction rctransaction = new Rctransaction();
rctransaction.setReceivings(rec);
If you try to call getReceivings after instantiating the object without setting it before you'll always get a NullPointerException. To avoid this, you can instantiate the Receivings object in the Rctransaction constructor.

Create a simple system to students and subjects

I started to study java and i'm try to do a simple system to associate students and subjects, my problem is how can i associate one student to many subjects, i hope you can help me.
Main Class
package exercicios;
public class Exercicio3_Main {
public static void main(String[] args) {
//Criando Alunos
Exercicio3_Aluno aluno[] = new Exercicio3_Aluno[3];
aluno[0] = new Exercicio3_Aluno("Douglas", "Telematica", 201391);
//Criando as Disciplinas
Exercicio3_Disciplina disciplina[] = new Exercicio3_Disciplina[7];
disciplina[0] = new Exercicio3_Disciplina("POO");
aluno[0].cadastrarDisciplina(disciplina[0]);
//aluno[0].listarAluno();
}
}
Student Class
package exercicios;
import java.util.ArrayList;
public class Exercicio3_Aluno {
public String nome;
public String curso;
private int matricula;
private ArrayList<Exercicio3_Disciplina> disciplina;
public Exercicio3_Aluno(String nome, String curso, int matricula) {
super();
this.nome = nome;
this.curso = curso;
this.matricula = matricula;
}
public void listarAluno(){
System.out.println("------------- ALUNO --------------");
System.out.println("Nome: " + this.getNome());
System.out.println("Curso: " + this.getCurso());
System.out.println("Matricula: " + this.getMatricula());
System.out.println("Disciplinas: " + disciplina);
System.out.println("----------------------------------");
}
//Metodos Acessores
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCurso() {
return curso;
}
public void setCurso(String curso) {
this.curso = curso;
}
public int getMatricula() {
return matricula;
}
public void setMatricula(int matricula) {
this.matricula = matricula;
}
public void cadastrarDisciplina(Exercicio3_Disciplina disciplina){
this.disciplina.add(disciplina);
}
}
Subjects Class
package exercicios;
public class Exercicio3_Disciplina {
public String nome;
private float nota1;
private float nota2;
private float nota3;
private float media;
public Exercicio3_Disciplina(String nome) {
super();
this.nome = nome;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public float getNota1() {
return nota1;
}
public void setNota1(float nota1) {
this.nota1 = nota1;
}
public float getNota2() {
return nota2;
}
public void setNota2(float nota2) {
this.nota2 = nota2;
}
public float getNota3() {
return nota3;
}
public void setNota3(float nota3) {
this.nota3 = nota3;
}
public float getMedia() {
return media;
}
public void setMedia(float media) {
this.media = media;
}
}
The output of this code is something like this:
Nome: Douglas
Curso: TLM
Matrícula: 102050
Disciplinas: Programação Orientada a Objetos
What i need is list many subjects to students, i know it's probably is very simple but i started to study this now and all of this is new for me ;D
Instead of one subject, you want multiple subjects on the student so use List<Subjects> on the student class and adjust the getters and setters as such. You can then add subjects to the list on the student.
Sample code
public static void main(String[] args) {
//Criando os Alunos
Exercicio3_Aluno aluno[] = new Exercicio3_Aluno[3];
aluno[0] = new Exercicio3_Aluno("Douglas", "TLM", 102050);
//Criando as Disciplinas
Exercicio3_Disciplina disciplina[] = new Exercicio3_Disciplina[7];
disciplina[0] = new Exercicio3_Disciplina("Programação Orientada a Objetos");
disciplina[1] = new Exercicio3_Disciplina("Sistemas Operacionais");
//Mostrando os dados do Aluno
aluno[0].cadastrarDisciplina(disciplina[0]);
aluno[0].cadastrarDisciplina(disciplina[1]);
aluno[0].listaAluno();
}
In your student method
//Lista o Aluno
public void listaAluno(){
System.out.println("--------- DADOS DO ALUNO --------");
System.out.println("Nome: " + this.nome);
System.out.println("Curso: " + this.curso);
System.out.println("Matrícula: " + this.matricula);
System.out.println("Disciplinas: ");
String disciplinasString = "";
for(Exercicio3_Disciplina disciplina : this.disciplinas)
{
disciplinasString = disciplinasString + disciplina.getNome());
}
System.out.println(disciplinasString);
System.out.println("---------------------------------");
}

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "ID"

I'm trying to make a program that asks for an ID. it stores the ID and if you want to search it, you type the ID and click "Search". The program will show information of the ID. (Name, Adress, Phone number, etc). The problem is that when i click "Search" it gives me this error(shown at title). I may have forgotten some information, if so please tell me. Im new to this website and Java and i couldn't find anything on google that would FIX it.
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "ID"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
Code
...ArrayList<Trabajador> listaTrabajadores = new ArrayList<Trabajador>();
.
...private void bt_BuscarActionPerformed(java.awt.event.ActionEvent evt) {
String idStr = lb_ID.getText();
if("".equals(idStr)) {
mostrarMensaje("Please enter an ID.");
return;
}
try {
int id = Integer.parseInt(idStr);
for (Trabajador trabajador : listaTrabajadores) {
if(trabajador.getId() == id){
jt_Nombre.setText(trabajador.getNombre());
jt_Direccion.setText(trabajador.getDireccion());
jt_Telefono.setText(trabajador.getTelefono());
jt_Sueldo.setText(String.valueOf(trabajador.getSueldo()));
ComboBoxModel cbm = this.cb_Region.getModel();
for (int i = 0; i < cbm.getSize(); i++) {
if(cbm.getElementAt(i).toString().equals(trabajador.getRegion())) {
cbm.setSelectedItem(i);
return;
}
}
}
}
mostrarMensaje("ID not found");
} catch (Exception e) {
mostrarMensaje("ID has to be numeric");
}
}
"Trabajador" Class
public class Trabajador {
private int id;
private String nombre;
private String direccion;
private String telefono;
private int sueldo;
private String region;
public Trabajador() {
}
public Trabajador(int id, String nombre, String direccion, String telefono, int sueldo, String region) {
this.id = id;
this.nombre = nombre;
this.direccion = direccion;
this.telefono = telefono;
this.sueldo = sueldo;
this.region = region;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public int getSueldo() {
return sueldo;
}
public void setSueldo(int sueldo) {
this.sueldo = sueldo;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
}
The problem was that i was using the wrong object. I was using lb_ID instead of jt_ID at String idStr = lb_ID.getText();.

Categories

Resources