How to use #lombok.Builder.Default with java records - java

Before java 16 you would use a class with a lombok value annotation, because records didn't exist yet (except in preview). If you wanted a builder and wanted a field to have a default value, you would annotate it like so:
#Builder
#Value
public class SomeClass {
private final int id;
private final String someString;
#Builder.Default
private final String someOtherString = "DefaultVal";
}
This would generate the following class:
public final class SomeClass {
private final int id;
private final String someString;
private final String someOtherString;
SomeClass(int id, String someString, String someOtherString) {
this.id = id;
this.someString = someString;
this.someOtherString = someOtherString;
}
private static String $default$someOtherString() {
return "DefaultVal";
}
public static SomeClassBuilder builder() {
return new SomeClassBuilder();
}
public int getId() {
return this.id;
}
public String getSomeString() {
return this.someString;
}
public String getSomeOtherString() {
return this.someOtherString;
}
public boolean equals(final Object o) {
if (o == this) return true;
if (!(o instanceof SomeClass)) return false;
final SomeClass other = (SomeClass) o;
if (this.getId() != other.getId()) return false;
final Object this$someString = this.getSomeString();
final Object other$someString = other.getSomeString();
if (this$someString == null ? other$someString != null : !this$someString.equals(other$someString))
return false;
final Object this$someOtherString = this.getSomeOtherString();
final Object other$someOtherString = other.getSomeOtherString();
if (this$someOtherString == null ? other$someOtherString != null : !this$someOtherString.equals(other$someOtherString))
return false;
return true;
}
public int hashCode() {
final int PRIME = 59;
int result = 1;
result = result * PRIME + this.getId();
final Object $someString = this.getSomeString();
result = result * PRIME + ($someString == null ? 43 : $someString.hashCode());
final Object $someOtherString = this.getSomeOtherString();
result = result * PRIME + ($someOtherString == null ? 43 : $someOtherString.hashCode());
return result;
}
public String toString() {
return "SomeClass(id=" + this.getId() + ", someString=" + this.getSomeString() + ", someOtherString=" + this.getSomeOtherString() + ")";
}
public static class SomeClassBuilder {
private int id;
private String someString;
private String someOtherString$value;
private boolean someOtherString$set;
SomeClassBuilder() {
}
public SomeClassBuilder id(int id) {
this.id = id;
return this;
}
public SomeClassBuilder someString(String someString) {
this.someString = someString;
return this;
}
public SomeClassBuilder someOtherString(String someOtherString) {
this.someOtherString$value = someOtherString;
this.someOtherString$set = true;
return this;
}
public SomeClass build() {
String someOtherString$value = this.someOtherString$value;
if (!this.someOtherString$set) {
someOtherString$value = SomeClass.$default$someOtherString();
}
return new SomeClass(id, someString, someOtherString$value);
}
public String toString() {
return "SomeClass.SomeClassBuilder(id=" + this.id + ", someString=" + this.someString + ", someOtherString$value=" + this.someOtherString$value + ")";
}
}
}
Now that we are well beyond java 16 and records have been added, I was trying to get this to work with those records. #Builder seems to work fine, but how can I use #Builder.Default with records?
#Builder
public record SomeClass(
int id,
String someString,
#Builder.Default
String someOtherString = "DefaultVal"
) {
}
The above code obviously doesn't work, because you can't assign a value in a record property definition. Is there a way to use #Builder.Default with records? For instance, can #Builder.ObtainVia be used for this or does that really only work with toBuilder()?

If you're looking to solve default values you can use this:
public record SomeClass(
int id,
String someString,
String someOtherString){
public SomeClass(){
this(UUID.randomUUID(), "default","default");
}
}

Related

Java Object in list doesn't get found

I have a problem. I have the following class:
public class Cross implements Comparable<Cross> {
private Long openTime;
private String market;
private String coin;
private String period;
private String metric1;
private String metric2;
private Double close;
private String trend;
public Long getOpenTime() {
return this.openTime;
}
public void setOpenTime(long openTime) {
this.openTime = openTime;
}
public String getMarket() {
return this.market;
}
public void setMarket(String market) {
this.market = market;
}
public String getCoin() {
return this.coin;
}
public void setCoin(String coin) {
this.coin = coin;
}
public String getPeriod() {
return this.period;
}
public void setPeriod(String period) {
this.period = period;
}
public String getMetric1() {
return this.metric1;
}
public void setMetric1(String metric1) {
this.metric1 = metric1;
}
public String getMetric2() {
return this.metric2;
}
public void setMetric2(String metric2) {
this.metric2 = metric2;
}
public Double getClose() {
return this.close;
}
public void setClose(double close) {
this.close = close;
}
public String getTrend() {
return this.trend;
}
#Override
public boolean equals(Object object) {
if (object != null && object instanceof Cross) {
Cross cross = (Cross) object;
return (
openTime.equals(cross.getOpenTime()) &&
market.equals(cross.getMarket()) &&
coin.equals(cross.getCoin()) &&
period.equals(cross.getPeriod()) &&
metric1.equals(cross.getMetric1()) &&
metric2.equals(cross.getMetric2())
);
}
return false;
}
#Override
public int compareTo(Cross o) {
return this.getOpenTime().compareTo(o.getOpenTime());
}
}
Now I have a list containing 500 objects of these elements. Here are the first 4 shown:
{ openTime='1504332000000', market='USDT', coin='ETH', period='2h', metric1='EMA12', metric2='EMA26', close='363.7', trend='Down'}
{ openTime='1504663200000', market='USDT', coin='ETH', period='2h', metric1='EMA12', metric2='EMA26', close='325.73', trend='Up'}
{ openTime='1504879200000', market='USDT', coin='ETH', period='2h', metric1='EMA12', metric2='EMA26', close='294.05', trend='Down'}
{ openTime='1505181600000', market='USDT', coin='ETH', period='2h', metric1='EMA12', metric2='EMA26', close='304.41', trend='Up'}
In a variable I have stored the epoch of a specific datetime and with that I want to find the first valid cross, so I tried this:
private Cross getValidCross(List<Cross> crossList, LocalDateTime runDateTimeGMT0) {
long searchEpoch = runDateTimeGMT0.toEpochSecond(ZoneOffset.UTC) * 1000;
return crossList.stream().filter(cross -> cross.getOpenTime() < searchEpoch).max(Cross::compareTo).orElse(null);
}
But this code returns the value null When my searchEpoch is for example: 1514764800000. In the list I do see multiple objects that have a lower openTime than the searchEpoch. The result I want is the cross with the highest openTime, but it still has to be smaller than the searchEpoch.
Here is the error I get:
runDateTimeGMT0: 2018-01-01T00:00
Exception in thread "main" java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at com.hatop.drivers.SimulatorDriver.run(SimulatorDriver.java:297)
at com.hatop.drivers.HatopDriver.main(HatopDriver.java:120)
Caused by: java.lang.NullPointerException: Cannot invoke "com.hatop.models.Cross.getTrend()" because the return value of "com.hatop.drivers.HatopDriver.getValidCross(List<Cross>, LocalDateTime)"
is null
at com.hatop.strategies.modules.module_java001.run(module_java001.java:186)
... 6 more
Why is my return value null?
This is caused due to the value the argument runDateTimeGMT0 is given and this:
long searchEpoch = runDateTimeGMT0.toEpochSecond(ZoneOffset.UTC) * 1000;
Since this is working:
public class Demo {
private static Cross getValidCross(List<Cross> crossList, LocalDateTime runDateTimeGMT0) {
long searchEpoch = 1514764800000L;
return crossList.stream()
.filter(cross -> cross.getOpenTime() < searchEpoch)
.max(Cross::compareTo)
.orElse(null);
}
#SneakyThrows
public static void main(String[] args) {
List<Cross> crosses = Arrays.asList(
new Cross(1504332000000L, "USDT", "ETH", "2h", "EMA12", "EMA26", 363.7, "Down"),
new Cross(1504663200000L, "USDT", "ETH", "2h", "EMA12", "EMA26", 325.73, "Up"),
new Cross(1504879200000L, "USDT", "ETH", "2h", "EMA12", "EMA26", 294.05, "Down"),
new Cross(1505181600000L, "USDT", "ETH", "2h", "EMA12", "EMA26", 304.41, "Up")
);
Cross validCross = getValidCross(crosses, null);
System.out.println(validCross);
}
}
Output:
Cross(openTime=1505181600000, market=USDT, coin=ETH, period=2h, metric1=EMA12, metric2=EMA26, close=304.41, trend=Up)
By the way, equals() is implemented without hashcode() - a recipe for problems.
I tested you code by passing the value in a proper Cross constructor, as it appears in your list and it works fine. In particular, openingTime is passed as primitive type long.
The issue is NOT in the filter, as you can definitely use any operator with Long type.
In my opinion, there is something wrong in the file format of your Cross object. Highly likely is because of the openingTime field's value, which is probably converted in the wrong value.
Here is the test I wrote:
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;
public class TestCross {
public static void main(String[] args) {
List<Cross> crossList = List.of(new Cross(1504332000000L,"USDT", "ETH", "2h","EMA12", "EMA26",363.7,"Down" ),
new Cross(1505181600000L,"USDT", "ETH", "2h","EMA12", "EMA26",304.41,"Up" ),
new Cross(1504663200000L,"USDT", "ETH", "2h","EMA12", "EMA26",325.73,"Up" ),
new Cross(1504879200000L,"USDT", "ETH", "2h","EMA12", "EMA26",294.05,"Down" ));
Cross cross = new TestCross().getValidCross(crossList, LocalDateTime.now());
System.out.println(cross);
}
private Cross getValidCross(List<Cross> crossList, LocalDateTime runDateTimeGMT0) {
long searchEpoch = runDateTimeGMT0.toEpochSecond(ZoneOffset.UTC) * 1000;
return crossList.stream().filter(cross -> cross.getOpenTime() < searchEpoch).max(Cross::compareTo).orElse(null);
}
}
Cross class
public class Cross implements Comparable<Cross> {
public Cross(Long openTime, String market, String coin, String period, String metric1, String metric2, Double close,
String trend) {
super();
this.openTime = openTime;
this.market = market;
this.coin = coin;
this.period = period;
this.metric1 = metric1;
this.metric2 = metric2;
this.close = close;
this.trend = trend;
}
private Long openTime;
private String market;
private String coin;
private String period;
private String metric1;
private String metric2;
private Double close;
private String trend;
public Long getOpenTime() {
return this.openTime;
}
public void setOpenTime(long openTime) {
this.openTime = openTime;
}
public String getMarket() {
return this.market;
}
public void setMarket(String market) {
this.market = market;
}
public String getCoin() {
return this.coin;
}
public void setCoin(String coin) {
this.coin = coin;
}
public String getPeriod() {
return this.period;
}
public void setPeriod(String period) {
this.period = period;
}
public String getMetric1() {
return this.metric1;
}
public void setMetric1(String metric1) {
this.metric1 = metric1;
}
public String getMetric2() {
return this.metric2;
}
public void setMetric2(String metric2) {
this.metric2 = metric2;
}
public Double getClose() {
return this.close;
}
public void setClose(double close) {
this.close = close;
}
public String getTrend() {
return this.trend;
}
#Override
public boolean equals(Object object) {
if (object != null && object instanceof Cross) {
Cross cross = (Cross) object;
return (
openTime.equals(cross.getOpenTime()) &&
market.equals(cross.getMarket()) &&
coin.equals(cross.getCoin()) &&
period.equals(cross.getPeriod()) &&
metric1.equals(cross.getMetric1()) &&
metric2.equals(cross.getMetric2())
);
}
return false;
}
#Override
public String toString() {
return "Cross [openTime=" + openTime + ", market=" + market + ", coin=" + coin + ", period=" + period
+ ", metric1=" + metric1 + ", metric2=" + metric2 + ", close=" + close + ", trend=" + trend + "]";
}
#Override
public int compareTo(Cross o) {
return this.getOpenTime().compareTo(o.getOpenTime());
}
}
And here is the output:
Cross [openTime=1505181600000, market=USDT, coin=ETH, period=2h, metric1=EMA12, metric2=EMA26, close=304.41, trend=Up]

Lombok Maven different of Lombok in Eclipse or STS

I have a delta between compile by Maven and compile by Eclipse. By Maven is OK but not by Eclipse.
In compile by Eclipse, it misses the #ConstructorProperties({ "id", "profile" }) annotation on the constructor that has both parameters.
My java file:
#Data
#AllArgsConstructor
public class Author {
private String id;
private String profile;
}
Full class by Maven (OK):
import java.beans.ConstructorProperties;
public class Author {
private String id;
private String profile;
public void setId(String id) {
this.id = id;
}
public void setProfile(String profile) {
this.profile = profile;
}
#Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof Author)) {
return false;
}
final Author other = (Author) o;
if (!other.canEqual(this)) {
return false;
}
final Object this$id = getId();
final Object other$id = other.getId();
if (this$id == null ? other$id != null : !this$id.equals(other$id)) {
return false;
}
final Object this$profile = getProfile();
final Object other$profile = other.getProfile();
return this$profile == null ? other$profile == null : this$profile.equals(other$profile);
}
protected boolean canEqual(Object other) {
return other instanceof Author;
}
#Override
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $id = getId();
result = result * 59 + ($id == null ? 43 : $id.hashCode());
final Object $profile = getProfile();
result = result * 59 + ($profile == null ? 43 : $profile.hashCode());
return result;
}
#Override
public String toString() {
return "Author(id=" + getId() + ", profile=" + getProfile() + ")";
}
#ConstructorProperties({ "id", "profile" })
public Author(String id, String profile) {
this.id = id;
this.profile = profile;
}
public String getId() {
return id;
}
public String getProfile() {
return profile;
}
}
Full class by Eclipse:
public class Author {
private String id;
private String profile;
public String getId() {
return id;
}
public String getProfile() {
return profile;
}
public void setId(String id) {
this.id = id;
}
public void setProfile(String profile) {
this.profile = profile;
}
#Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof Author)) {
return false;
}
final Author other = (Author) o;
if (!other.canEqual(this)) {
return false;
}
final Object this$id = getId();
final Object other$id = other.getId();
if (this$id == null ? other$id != null : !this$id.equals(other$id)) {
return false;
}
final Object this$profile = getProfile();
final Object other$profile = other.getProfile();
return this$profile == null ? other$profile == null : this$profile.equals(other$profile);
}
protected boolean canEqual(Object other) {
return other instanceof Author;
}
#Override
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $id = getId();
result = result * 59 + ($id == null ? 43 : $id.hashCode());
final Object $profile = getProfile();
result = result * 59 + ($profile == null ? 43 : $profile.hashCode());
return result;
}
#Override
public String toString() {
return "Author(id=" + getId() + ", profile=" + getProfile() + ")";
}
public Author(String id, String profile) {
this.id = id;
this.profile = profile;
}
}
#tobias_k find solution:
Eclipse need same version of Lombok installed that Maven project use.

Json Deserializer - How to get data from parent JSON object

I am using Spring MVC and spring take care of converting json to Objects in controller. But my json structure is different then class structure. So I have written my own deserializer. But I am getting problem to accessing values of parent object in JSON. I think it is better to explain my problem using some example -
I have following JSON to deserialize
{
id: 1,
children: {
"name1": "value1",
"name2": "value2"
}
}
I have following classes (Sample Code) -
public class Parent {
private Integer id;
#JsonDeserialize(using= ChildrenDeserializer.class)
private List<Child> children;
//... Getter/setters
}
public class Child {
private Integer id;
private String name;
private String value;
//...getters/setters
}
public class ChildrenDeserializer extends JsonDeserializer<List<Child>> {
#Override
public List<Child> deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
List<Child> children = new ArrayList<>();
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
Iterator<Map.Entry<String, JsonNode>> fieldsIterator = node.fields();
while (fieldsIterator.hasNext()) {
Map.Entry<String, JsonNode> field = fieldsIterator.next();
String name = field.getKey();
String value = field.getValue().textValue();
Child child = new Child();
//Here I want to get parentId from the Json. Is it possible??
Integer childId = childRepository.searchChildIdByParentId(parentId, name);
child.setId(childId);
child.setName(name);
child.setValue(value);
children.add(child);
}
return children;
}
}
Is there any way to get parentId (which is 1 in above example) while deserializing children??
Having the same need , I come across with your question . My solution to the problem is on the parent constructor: When create the parent class, set the correct property in the child class.
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
public class JsonUnitTest {
private static final Logger logger = LogManager.getLogger(JsonUnitTest.class);
#Test
public void unit() {
// test objects
final int parentId = 1;
final int childId = 2;
final ParentClass parent = new ParentClass(parentId);
final ChildClass child = new ChildClass(childId);
parent.setChild(child);
// serialize
final String json = JsonHelper.toJson(parent);
logger.info(json);
logger.info(parent);
// deserialize
final ParentClass newParent = JsonHelper.fromJson(json, ParentClass.class);
// asserts
Assert.assertNotNull(newParent);
Assert.assertEquals(newParent, parent);
}
The result of the test is
[main] INFO JsonUnitTest:29 {"id":1,"child":{"childId":2}}
[main] INFO JsonUnitTest:30 ParentClass [id=1, child=ChildClass [parentId=1, childId=2]]
PASSED: unit
Here the rest of the code :
public static class ParentClass {
public static final String idKey = "id";
public static final String childKey = "child";
#JsonProperty(idKey)
private int id;
#JsonProperty(childKey)
private ChildClass child;
public ParentClass(int id) {
this.id = id;
}
#JsonCreator
public ParentClass(
#JsonProperty(idKey) int id,
#JsonProperty(childKey) ChildClass child) {
super();
this.id = id;
setChild(child);
}
#JsonProperty(idKey)
public int getId() {
return id;
}
#JsonProperty(idKey)
public void setId(int id) {
this.id = id;
}
#JsonProperty(childKey)
public ChildClass getChild() {
return child;
}
#JsonProperty(childKey)
public void setChild(ChildClass child) {
this.child = child;
child.setParentId(id);
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((child == null) ? 0 : child.hashCode());
result = prime * result + id;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ParentClass other = (ParentClass) obj;
if (child == null) {
if (other.child != null)
return false;
} else if (!child.equals(other.child))
return false;
if (id != other.id)
return false;
return true;
}
#Override
public String toString() {
return "ParentClass [id=" + id + ", child=" + child + "]";
}
}
public static class ChildClass {
public static final String parentIdKey = "../" + ParentClass.idKey;
public static final String childIdKey = "childId";
private int parentId;
private int childId;
#JsonCreator
public ChildClass(#JsonProperty(childIdKey) int childId) {
super();
this.childId = childId;
}
#JsonIgnore
public int getParentId() {
return parentId;
}
#JsonProperty(parentIdKey)
public void setParentId(int parentId) {
this.parentId = parentId;
}
#JsonProperty(childIdKey)
public int getChildId() {
return childId;
}
#JsonProperty(childIdKey)
public void setChildId(int childId) {
this.childId = childId;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + childId;
result = prime * result + parentId;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ChildClass other = (ChildClass) obj;
if (childId != other.childId)
return false;
if (parentId != other.parentId)
return false;
return true;
}
#Override
public String toString() {
return "ChildClass [parentId=" + parentId + ", childId=" + childId + "]";
}
}
}

Rhino Evaluating a javascript object in Java

Im quite new to Rhino and trying to convert a javascript object to a java object but unable to do so. It doesnt seem to evaluate properly.
The javascript that I have is,
var myObject = new Object();
myObject.string1 = 'Hello';
myObject.string2 = 'World';
myObject.id = 1;
var parser = new Packages.com.MyParser();
var returnStr = parser.PrintObj(myObject);
And I have the following java class that I want to evaluate this to,
public class Person extends ScriptableObject {
private int id;
private String string1;
private String string2;
public Person() {}
public void jsConstructor() {
this.string1 = "";
this.string2 = "";
this.id = 0;
}
public int getID()
{
return this.id;
}
public void jsSet_id(int value)
{
this.id = value;
}
public int jsGet_id()
{
return this.id;
}
public String jsGet_string1()
{
return this.string1;
}
public void jsSet_string1(String value)
{
this.string1 = value;
}
public String jsGet_string2() {
return this.string2;
}
public void jsSet_string2(String value)
{
this.string2 = value;
}
#Override
public String toString() {
return id + " " + string1 + " " + string2;
}
#Override
public String getClassName() {
return "Person";
}
And the skeleton of my parser is,
public class MyParser {
public String PrintObj(ScriptableObject obj) {
// Need to convert to Person object here
// Obviously casting doesnt work here
return null;
}
}
Thanks
OK figured it out !
First of all i needed to define the class in javascript as. It was complaining at first it couldn't find the class without the namespace "com". Had to add that...
defineClass("com.Person")
var myObject = new Person();
myObject.string1 = 'Hello';
myObject.string2 = 'World';
myObject.id = 1;
var parser = new Packages.com.MyParser();
var returnStr = parser.PrintObj(myObject);
And then in the parser I added the following,
public String PrintObj(ScriptableObject obj) {
try {
Person pObj = (Person)Context.jsToJava(obj, Person.class);
System.out.println("Printing person: " + pObj);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}

oracle db id column auto generate JPA JSF

I have a basic problem with my oracle database table whereas I use JPA.
My problem is, I create the table in the database by adding it an ID column. When I turn back to my JPA project, and when I try to create new entry it doesn't create ID for the new one. It always says: An error occurred attempting to roll back the transaction.
I search about the issue. It basically doesn't auto-generate the ID value. Here is my JPA controller class:
#Entity
#Table(name = "PROJECTS", catalog = "", schema = "PROJETAKIP")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Projects.findAll", query = "SELECT p FROM Projects p"),
#NamedQuery(name = "Projects.findById", query = "SELECT p FROM Projects p WHERE p.id = :id"),
#NamedQuery(name = "Projects.findByProject", query = "SELECT p FROM Projects p WHERE p.project = :project")})
public class Projects implements Serializable {
private static final long serialVersionUID = 1L;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Id
#Basic(optional = false)
#Column(name = "ID", nullable = false, precision = 0, scale = -127)
#GeneratedValue(strategy= GenerationType.SEQUENCE)
private BigDecimal id;
#Column(name = "PROJECT", length = 255)
private String project;
public Projects() {
}
public Projects(BigDecimal id) {
this.id = id;
}
public BigDecimal getId() {
return id;
}
public void setId(BigDecimal id) {
this.id = id;
}
public String getProject() {
return project;
}
public void setProject(String project) {
this.project = project;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Projects)) {
return false;
}
Projects other = (Projects) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.ibb.souce.Projects[ id=" + id + " ]";
}
}
and here is my JSFClass:
#ManagedBean(name = "projectsController")
#SessionScoped
public class ProjectsController implements Serializable {
#Resource
private UserTransaction utx = null;
#PersistenceUnit(unitName = "DenemelerPU")
private EntityManagerFactory emf = null;
private Projects current;
private DataModel items = null;
private ProjectsJpaController jpaController = null;
private PaginationHelper pagination;
private int selectedItemIndex;
public ProjectsController() {
}
public Projects getSelected() {
if (current == null) {
current = new Projects();
selectedItemIndex = -1;
}
return current;
}
private ProjectsJpaController getJpaController() {
if (jpaController == null) {
jpaController = new ProjectsJpaController(utx, emf);
}
return jpaController;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return getJpaController().getProjectsCount();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(getJpaController().findProjectsEntities(getPageSize(), getPageFirstItem()));
}
};
}
return pagination;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (Projects) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new Projects();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getJpaController().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ProjectsCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareEdit() {
current = (Projects) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Edit";
}
public String update() {
try {
getJpaController().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ProjectsUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String destroy() {
current = (Projects) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
performDestroy();
recreatePagination();
recreateModel();
return "List";
}
public String destroyAndView() {
performDestroy();
recreateModel();
updateCurrentItem();
if (selectedItemIndex >= 0) {
return "View";
} else {
// all items were removed - go back to list
recreateModel();
return "List";
}
}
private void performDestroy() {
try {
getJpaController().destroy(current.getId());
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ProjectsDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
private void updateCurrentItem() {
int count = getJpaController().getProjectsCount();
if (selectedItemIndex >= count) {
// selected index cannot be bigger than number of items:
selectedItemIndex = count - 1;
// go to previous page if last page disappeared:
if (pagination.getPageFirstItem() >= count) {
pagination.previousPage();
}
}
if (selectedItemIndex >= 0) {
current = getJpaController().findProjectsEntities(1, selectedItemIndex).get(0);
}
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
private void recreateModel() {
items = null;
}
private void recreatePagination() {
pagination = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return "List";
}
public String previous() {
getPagination().previousPage();
recreateModel();
return "List";
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(getJpaController().findProjectsEntities(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(getJpaController().findProjectsEntities(), true);
}
#FacesConverter(forClass = Projects.class)
public static class ProjectsControllerConverter implements Converter {
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
ProjectsController controller = (ProjectsController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "projectsController");
return controller.getJpaController().findProjects(getKey(value));
}
java.math.BigDecimal getKey(String value) {
java.math.BigDecimal key;
key = new java.math.BigDecimal(value);
return key;
}
String getStringKey(java.math.BigDecimal value) {
StringBuffer sb = new StringBuffer();
sb.append(value);
return sb.toString();
}
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Projects) {
Projects o = (Projects) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Projects.class.getName());
}
}
}
}
When I assign the ID manually it works perfectly. But what I want is, it has to auto-generate the value. How to overcome this?
my trigger: DELIMITER ##
CREATE OR REPLACE TRIGGER PROJETAKIP.PROJECTS_TRIGGER BEFORE INSERT ON PROJECTS REFERENCING NEW AS NEW FOR EACH ROW BEGIN SELECT PROJECTS_SEQUENCE.nextval INTO :NEW.ID FROM dual;END; ##
DELIMITER ;
Sequence startegy
This is how you should use the sequence generator:
#GeneratedValue(strategy= GenerationType.SEQUENCE, generator="seq")
And on the class: (eg. after the #Entity)
#SequenceGenerator(name="seq", sequenceName="PROJECTS_SEQUENCE", initialValue=1)
This should work for you.
While saving the object i had the same error.
My reason was because of adding MIN range of 3 digits to id value.
By default auto generated id will start from 1, 2, 3 ...
I did:
#Id #GeneratedValue
#Basic(optional = false)
#Size(min = 1, max = 64, message = "ID must be between 1 and 64 characters")
private String id;
So - in your case - be careful with your id annotations - try to launch without scale, min and max values - see the result. For example, try:
#Id
#Basic(optional = false)
#Column(name = "ID")
#GeneratedValue(strategy= GenerationType.AUTO)
private BigDecimal id;

Categories

Resources