I have a table, and I want to change state field of mapped table from 1 to 0 when I press delete button. Here is the logic.
It is my mapped table
#Entity
#Table(name = "POSITION_ACCOUNT")
public class PositionAccount {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "ID", columnDefinition = "NUMERIC(15, 0)",unique = true,nullable = false)
private Long id;
public Long getId() {
return id;
}
#Column(name = "ACCT_NUMBER")
private String accountNumber;
public String getAccountNumber() { return accountNumber; }
#Column(name = "ACCT_NAME")
private String accountName;
public String getAccountName() {
return accountName;
}
#Column(name = "CURRENCY_CODE")
private String currencyCode;
public String getCurrencyCode() {
return currencyCode;
}
#Column(name = "BALANCE")
private BigDecimal balance = new BigDecimal("0");
public BigDecimal getBalance() {
return balance;
}
#Column(name = "ACCT_TYPE")
private String accountType;
public String getAccountType() { return accountType; }
#Column(name = "STATE")
private int state = 1;
public int getState() {
return state;
}
public void setId(Long id) {
this.id = id;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public void setCurrencyCode(String currencyCode) {
this.currencyCode = currencyCode;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
public void setState(int state) {
this.state = state;
}
public void setAccountType(String accountType) { this.accountType = accountType; }
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PositionAccount that = (PositionAccount) o;
return !(id != null ? !id.equals(that.id) : that.id != null);
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
#Override
public String toString() {
return "PositionAccount{" +
"id=" + id +
", accountNumber='" + accountNumber + '\'' +
", accountName='" + accountName + '\'' +
", currencyCode='" + currencyCode + '\'' +
", balance=" + balance +
", state=" + state +
'}';
}
}
Here is my #ActionMethod
#Inject
private LoroNostroService service;
#Inject
private LoroNostroModel model;
#ActionMethod(ACTION_DELETE_ACCOUNT)
public void deleteAccount() {
PositionAccount account = tv_loro_nostro_accounts.getSelectionModel().getSelectedItem();
DeleteAccount input = new DeleteAccount();
input.setAccountId(account.getId());
input.setType(account.getAccountType());
input.setAccNum(account.getAccountNumber());
input.setAccName(account.getAccountName());
input.setCurrency(account.getCurrencyCode());
input.setBalance(account.getBalance());
input.setCurState(0);
service.deleteAccount(input, context.getTaskView(), result -> {
model.getAccounts().addAll(result.getAccount());
tv_loro_nostro_accounts.getSelectionModel().selectFirst();
});
}
where tv_loro_nostro_accounts is TableView from which I make a selection. DeleteAccount class is a class where I define all fields of my table with getters and setters. service.deleteAccount after some manipulations goes here:
#Path("deleteAccount")
#POST
public DeleteAccount deleteAccount(DeleteAccount model){
try {
model = operationService.execute(model,(result, userDetails) -> {
PositionAccount a = new PositionAccount();
a.setAccountType(result.getType());
a.setAccountNumber(result.getAccNum());
a.setAccountName(result.getAccName());
a.setCurrencyCode(result.getCurrency());
a.setState(0);
service.deleteAccount(a);
result.setState(OperationState.DONE);
return result;
});
}catch (AdcException e) {
logger.error("X: ", e);
model.setState(OperationState.ERROR);
model.setErrorText(e.getLocalizedMessage(model.getLocale()));
} catch (Exception e) {
logger.error("X: ", e);
model.setState(OperationState.ERROR);
model.setErrorText(e.getLocalizedMessage());
}
return model;
}
where service.deleteAccount is
public void deleteAccount(PositionAccount account){
repository.deleteAccount(account);
}
and repository.deleteAccount is
public void deleteAccount(PositionAccount account){
em.merge(account);
em.refresh(account);
}
When I run above, I receive error
Entity not managed; nested exception is java.lang.IllaegalArgumentException: Entity not managed
Please hrlp to fix above.
merge returnes the managed entity instance, so to make this not to throw exception do:
account = em.merge(account);
em.refresh(account);
However, refresh will overwrite all the changes, so it is not needed here. Your method should look like:
public void deleteAccount(PositionAccount account) {
em.merge(account);
}
Related
I can’t set the discipline values for my semester, when I work out the controller, I get all the data I need, but I can’t connect them, can anyone tell me with an experienced eye what is the reason? I am getting this kind of error:
Request processing failed; nested exception is
org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private int com.kushnirmark.spring.project.entity.Discipline.id] by reflection for persistent property [com.kushnirmark.spring.project.entity.Discipline#id] : Higher mathematics
Here is my entity Semestr:
package com.kushnirmark.spring.project.entity;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity
#Table(name = "semestr")
public class Semestr {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "name")
private String name;
#Column(name = "duration")
private String duration;
#Column(name = "status")
private boolean status = true;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "semestr_discipline",
joinColumns = #JoinColumn(name = "id_semestr"),
inverseJoinColumns = #JoinColumn(name = "id_discipline")
)
private List<Discipline> disciplineList;
public void addDisciplineToSemester(Discipline discipline) {
if (disciplineList == null) {
disciplineList = new ArrayList<>();
}
disciplineList.add(discipline);
}
public Semestr() {
}
public Semestr(int id, String name, String duration, boolean status) {
this.id = id;
this.name = name;
this.duration = duration;
this.status = status;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public List<Discipline> getDisciplineList() {
return disciplineList;
}
public void setDisciplineList(List<Discipline> disciplineList) {
this.disciplineList = disciplineList;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Semestr semestr = (Semestr) o;
if (id != semestr.id) return false;
if (status != semestr.status) return false;
if (name != null ? !name.equals(semestr.name) : semestr.name != null) return false;
return duration != null ? duration.equals(semestr.duration) : semestr.duration == null;
}
#Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (duration != null ? duration.hashCode() : 0);
result = 31 * result + (status ? 1 : 0);
return result;
}
#Override
public String toString() {
return "Semestr{" +
"id=" + id +
", name='" + name + '\'' +
", duration='" + duration + '\'' +
", status=" + status +
'}';
}
}
Controller :
#RequestMapping("/saveNewSemester")
public String saveNewSemester(#ModelAttribute("semestr") Semestr semestr,
#RequestParam(name = "AllDiscipline") String[] AllDiscipline,
Model model) {
List<Integer> list = Arrays.stream(AllDiscipline).map(Integer::parseInt).collect(Collectors.toList());
List<Discipline> disciplineSemestrList = service.getDisciplineList(list);
semestr.setDisciplineList(disciplineSemestrList);
service.saveNewSemester(semestr);
return "redirect:/semestr";
}
Here is my entity Discipline :
package com.kushnirmark.spring.project.entity;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
#Entity
#Table(name = "discipline")
public class Discipline {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "discipline")
private String discipline;
#Column(name = "status")
private boolean status = true;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "semestr_discipline",
joinColumns = #JoinColumn(name = "id_discipline"),
inverseJoinColumns = #JoinColumn(name = "id_semestr")
)
private List<Semestr> semestrList;
public void addSemesterToDiscipline(Semestr semestr) {
if (semestrList == null) {
semestrList = new ArrayList<>();
}
semestrList.add(semestr);
}
public Discipline() {
}
public Discipline(int id, String discipline, boolean status) {
this.id = id;
this.discipline = discipline;
this.status = status;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDiscipline() {
return discipline;
}
public void setDiscipline(String discipline) {
this.discipline = discipline;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public List<Semestr> getSemestrList() {
return semestrList;
}
public void setSemestrList(List<Semestr> semestrList) {
this.semestrList = semestrList;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Discipline that = (Discipline) o;
return id == that.id &&
status == that.status &&
Objects.equals(discipline, that.discipline);
}
#Override
public int hashCode() {
return Objects.hash(id, discipline, status);
}
#Override
public String toString() {
return "Discipline{" +
"id=" + id +
", discipline='" + discipline + '\'' +
", status=" + status +
'}';
}
}
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().
I have two tables
tbl_user_info
tbl_user_auth
I am trying to save data in both the tables sequentially but data is getting stored in first table and throwing me error as below :
{
"timestamp": "2020-06-15T11:17:06.540+0000",
"status": 500,
"error": "Internal Server Error",
"message": "could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement",
"path": "/user/register"
}
Entity classes are as follows :
UserAccount
#Entityd
#Table(name = "tbl_user_info")
public class UserAccount {
#Id
#GeneratedValue (strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
#Column(name = "name")
private String name;
#Column(name = "email")
private String email;
#Column(name = "mobile_number")
private String mobileNumber;
#Column(name = "password")
private String password;
#Column(name = "token")
private String token;
#Column(name = "admin")
private Integer admin;
#Column(name = "country_code")
private String countryCode;
#Column(name = "serial_number")
private String serialNumber;
protected UserAccount() {
}
public UserAccount(Integer id, String name, String email, String mobileNumber, String password, String token, Integer admin, String countryCode, String serialNumber) {
this.id = id;
this.name = name;
this.email = email;
this.mobileNumber = mobileNumber;
this.password = password;
this.token = token;
this.admin = admin;
this.countryCode = countryCode;
this.serialNumber = serialNumber;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public Integer getAdmin() {
return admin;
}
public void setAdmin(Integer admin) {
this.admin = admin;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserAccount that = (UserAccount) o;
return Objects.equals(id, that.id) &&
Objects.equals(name, that.name) &&
Objects.equals(email, that.email) &&
Objects.equals(mobileNumber, that.mobileNumber) &&
Objects.equals(password, that.password) &&
Objects.equals(token, that.token) &&
Objects.equals(admin, that.admin) &&
Objects.equals(countryCode, that.countryCode) &&
Objects.equals(serialNumber, that.serialNumber);
}
#Override
public int hashCode() {
return Objects.hash(id, name, email, mobileNumber, password, token, admin, countryCode);
}
#Override
public String toString() {
return "UserAccount{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", mobileNumber='" + mobileNumber + '\'' +
", password='" + password + '\'' +
", token='" + token + '\'' +
", admin=" + admin +
", countryCode='" + countryCode + '\'' +
", serialNumber='" + serialNumber + '\'' +
'}';
}
}
UserAuthInfo
#Entity
#Table(name = "tbl_user_auth")
public class UserAuthInfo implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
#Column(name = "client_id")
private String clientId;
#Column(name = "user_id")
private Integer userId;
#Column(name = "code")
private String code;
#Column(name = "access_token")
private String accessToken;
#Column(name = "refresh_token")
private String refreshToken;
#Column(name = "expires_in")
private Integer expiresIn;
#Column(name = "modified_datetime")
private String datetime;
public UserAuthInfo() {
}
public UserAuthInfo(Integer id, String clientId, Integer userId, String code, String accessToken, String refreshToken, Integer expiresIn, String datetime) {
this.id = id;
this.clientId = clientId;
this.userId = userId;
this.code = code;
this.accessToken = accessToken;
this.refreshToken = refreshToken;
this.expiresIn = expiresIn;
this.datetime = datetime;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
public Integer getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(Integer expiresIn) {
this.expiresIn = expiresIn;
}
public String getDatetime() {
return datetime;
}
public void setDatetime(String datetime) {
this.datetime = datetime;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserAuthInfo that = (UserAuthInfo) o;
return Objects.equals(id, that.id) &&
Objects.equals(clientId, that.clientId) &&
Objects.equals(userId, that.userId) &&
Objects.equals(code, that.code) &&
Objects.equals(accessToken, that.accessToken) &&
Objects.equals(refreshToken, that.refreshToken) &&
Objects.equals(expiresIn, that.expiresIn) &&
Objects.equals(datetime, that.datetime);
}
#Override
public int hashCode() {
return Objects.hash(id, clientId, userId, code, accessToken, refreshToken, expiresIn, datetime);
}
#Override
public String toString() {
return "UserAuthInfo{" +
"id=" + id +
", clientId='" + clientId + '\'' +
", userId=" + userId +
", code='" + code + '\'' +
", accessToken='" + accessToken + '\'' +
", refreshToken='" + refreshToken + '\'' +
", expiresIn=" + expiresIn +
", datetime=" + datetime +
'}';
}
}
Controller :
#PostMapping("register") // Needed parameter : All except id and token
public AuthResponse registerUser(#RequestBody UserAccount userAccount) throws NoSuchAlgorithmException {
if (userAccount == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Request Body can not be null");
jsonResponse = new JSONResponse();
if (!userAccountService.isEmailPresent(userAccount.getEmail())){
userAccount.setPassword(DigestUtils.md5Hex(userAccount.getPassword()));
return userAccountService.registerUser(userAccount);
}
throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"Email ID Already Exists");
}
Service :
public AuthResponse registerUser(UserAccount userAccount) throws NoSuchAlgorithmException {
UserAccount ua = userAccountRepository.save(userAccount);
String token = tokenService.createToken((ua.getId()));
//Saving the user id and newly created token in tbl_token_info
ua.setToken(token);
UserAccount ua1 = userAccountRepository.save(ua);
UserAuthInfo userAuthInfo = new UserAuthInfo();
userAuthInfo.setClientId(UtilityMethods.clientId);
userAuthInfo.setUserId(ua.getId());
String code = UtilityMethods.getCode(userAccount.getEmail(), userAccount.getPassword());
userAuthInfo.setCode(code);
String accessToken = UtilityMethods.getAccessToken(code);
String refreshToken = UtilityMethods.getRefreshToken(code);
userAuthInfo.setAccessToken(accessToken);
userAuthInfo.setRefreshToken(refreshToken);
userAuthInfo.setExpiresIn(3600);
userAuthInfo = userAuthService.saveUserAuth(userAuthInfo);
AuthResponse authResponse = new AuthResponse();
authResponse.setAccessToken(userAuthInfo.getAccessToken());
authResponse.setRefreshToken(userAuthInfo.getRefreshToken());
authResponse.setExpiresIn(60);
authResponse.setCreatedDateTime(UtilityMethods.getCurrentDateTime());
return authResponse;
}
Please guide what is wrong.
you must use relations between tables:
#OneToMany for 1-N composition relation in tables.
#Embedded for 1-1 relations
#ManyToOne for N-1 association relations in tables.
Don´t use bidirectional relations. Always unidirectional.
if you don´t use this, the mapping of the database could be wrong.
I have two table entity channel and channel_stats.I want to save data in tables using session.save().
channel_stats can contain duplicate entry with duplicate channel ID.
Can you please tell me how to do so using secondary table annotation in hibernate. or is there any other way? i tried with embedded and embedded annotation bit looks like its for same table
#Entity
#Table(name="channel_list")
public class Channel {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="channel_youtubeID")
private String channelYoutubeID;
#Column(name="channel_title")
private String channelTitle;
#Column(name="thumbnail_url")
private String thumbnailUrl;
#Column(name="active_bit")
private int activeBit;
#Embedded
private ChannelStats channelStats;
public Channel() {
}
public Channel(String channelYoutubeID, String channelTitle, String thumbnailUrl, int activeBit,
ChannelStats channelStats) {
super();
this.channelYoutubeID = channelYoutubeID;
this.channelTitle = channelTitle;
this.thumbnailUrl = thumbnailUrl;
this.activeBit = activeBit;
this.channelStats = channelStats;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getChannelYoutubeID() {
return channelYoutubeID;
}
public void setChannelYoutubeID(String channelYoutubeID) {
this.channelYoutubeID = channelYoutubeID;
}
public String getChannelTitle() {
return channelTitle;
}
public void setChannelTitle(String channelTitle) {
this.channelTitle = channelTitle;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
public int getActiveBit() {
return activeBit;
}
public void setActiveBit(int activeBit) {
this.activeBit = activeBit;
}
public ChannelStats getChannelStats() {
return channelStats;
}
public void setChannelStats(ChannelStats channelStats) {
this.channelStats = channelStats;
}
#Override
public String toString() {
return "Channel [id=" + id + ", channelYoutubeID=" + channelYoutubeID + ", channelTitle=" + channelTitle
+ ", thumbnailUrl=" + thumbnailUrl + ", activeBit=" + activeBit + ", channelStats=" + channelStats
+ "]";
}
}
#Embeddable
#Table(name="channel_stats")
public class ChannelStats {
#Column(name="channelID")
private String channelID;
#Column(name="viewCount")
private long viewCount;
#Column(name="commentCount")
private long commentCount;
#Column(name="subscriberCount")
private long subscriberCount;
#Column(name="hiddenSubscriberCount")
private boolean hiddenSubscriberCount;
#Column(name="videoCount")
private long videoCount;
public ChannelStats() {
}
public ChannelStats(String channelID, long viewCount, long commentCount, long subscriberCount,
boolean hiddenSubscriberCount, long videoCount) {
super();
this.channelID = channelID;
this.viewCount = viewCount;
this.commentCount = commentCount;
this.subscriberCount = subscriberCount;
this.hiddenSubscriberCount = hiddenSubscriberCount;
this.videoCount = videoCount;
}
public String getChannelID() {
return channelID;
}
public void setChannelID(String channelID) {
this.channelID = channelID;
}
public long getViewCount() {
return viewCount;
}
public void setViewCount(long viewCount) {
this.viewCount = viewCount;
}
public long getCommentCount() {
return commentCount;
}
public void setCommentCount(long commentCount) {
this.commentCount = commentCount;
}
public long getSubscriberCount() {
return subscriberCount;
}
public void setSubscriberCount(long subscriberCount) {
this.subscriberCount = subscriberCount;
}
public boolean isHiddenSubscriberCount() {
return hiddenSubscriberCount;
}
public void setHiddenSubscriberCount(boolean hiddenSubscriberCount) {
this.hiddenSubscriberCount = hiddenSubscriberCount;
}
public long getVideoCount() {
return videoCount;
}
public void setVideoCount(long videoCount) {
this.videoCount = videoCount;
}
#Override
public String toString() {
return "ChannelStats [channelID=" + channelID + ", viewCount=" + viewCount + ", commentCount=" + commentCount
+ ", subscriberCount=" + subscriberCount + ", hiddenSubscriberCount=" + hiddenSubscriberCount
+ ", videoCount=" + videoCount + "]";
}
}
As I understand the question, #Embeddable is not what you want in this case. #Embeddable and #Embedded is used when you don't want a separate second table. Since you want a separate table to have the ChannelStat data, it seems like you are trying to create a #OneToMany relationship where one Channel object can have multiple ChannelStat objects.
So your Channel class should have
#OneToMany( mappedBy = "channel", cascade = CascadeType.ALL )
private List<ChannelStat> channelStat;
Instead of
#Embedded
private ChannelStats channelStats;
And your ChannelStat class should have
public class ChannelStats {
// Other variables and their getters and setters
#ManyToOne( cascade = CascadeType.ALL )
#JoinColumn( name = "id" )
private Channel channel;
}
Read here for more information.
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?