Could someone explain what is wrong with this and is there a workaround?
private static final String parentField = AbstractType_.parent.getName();
#OneToMany(fetch = FetchType.EAGER, orphanRemoval = true, mappedBy = parentField)
private List<AbstractType> children = new ArrayList<AbstractType>();
In eclipse, this shows and error on the #OneToMany line:
While this would be fine:
The value for annotation attribute OneToMany.mappedBy must be a constant expression.
Also the Maven build fails because of this.
Then again, this will work fine.
private static final String test = "";
#OneToMany(fetch = FetchType.EAGER, orphanRemoval = true, mappedBy = test)
private List<AbstractType> children = new ArrayList<AbstractType>();
UPDATE:
What is happening here, that I wish to get the field name via metamodel, but one can not refer to it at 'mappedBy' attribute.
Related
I have a class defined in a class library like so:
Classlib1 - Client
public class client{
[Required]
public string Firstname {get; set;}
...
[RegularExpression(#"^(?:\d{9}|\d{3}-\d{2}-\d{4}|)$")]
public string SocialSecurityNumber {get; set;}
}
I also have a Test library where I want to ensure that my RegularExpression Attribute Validation is working.
Testlib
[TestMethod]
public void ThrowAnErrorOnSSNWithTooManyDigits(){
var client = new Client(){
Firstname = "Mickey",
...
SocialSecurityNumber = "1234567890123"
};
var vResults = new List<ValidationResult>();
var context = new ValidationContext(client){MemberName = "SocialSecurityNumber"};
var result = Validator.TryValidateProperty(client.SocialSecurityNumber, context, vResults);
Assert.IsFalse(result)
}
However, my Assertion always fails because result always equals true. I tried changing my validator to validate a required firstname instead of SocialSecurityNumber thinking that my RegEx wasn't quite right -- however, that returns true as well -- even if I set Firstname = ""
What do I need to do to get the Validator working in my Test classlib?
So, In combing through my project once again, I realized that the Test project that I added was actually targeting .Net4.6 while the rest of my projects are all targeting .Net Core 2.0.
I added a new .NetCore Test project and copied all my tests in there and everything worked as expected.
I've succeeded to successfully construct a REST API using APEX language defined with an annotation: #RestResource.
I also wrote a matching Unit test procedure with #isTest annotation. The execution of the REST API triggered by a HTTP GET with two input parameters works well, while the Unit Test execution, returns a "null" value list resulting from the SOQL query shown below:
String mycase = inputs_case_number; // for ex. '00001026'
sObject[] sl2 = [SELECT Id, CaseNumber FROM Case WHERE CaseNumber = :mycase LIMIT 1];
The query returns:
VARIABLE_ASSIGNMENT [22]|sl2|[]|0x1ffefea6
I've also tried to execute it with a RunAs() method (see code below), using a dynamically created Salesforce test user, not anonymous, connected to a more powerful profile, but still receiving a "null" answer at the SOQL query. The new profile defines "View All" permission for Cases. Other SOQL queries to objects like: "User" and "UserRecordAccess" with very similar construction are working fine, both for REST APEX and Test APEX.
Is there a way to configure an access permission for Unit test (#isTest) to read the Case object and a few fields like: Id and CaseNumber. Is this error related to the "Tooling API" function and how can we fix this issue in the test procedure?
Code attachment: Unit Test Code
#isTest
private class MyRestResource1Test {
static testMethod void MyRestRequest() {
// generate temporary test user object and assign to running process
String uniqueUserName = 'standarduser' + DateTime.now().getTime() + '#testorg.com';
Profile p = [SELECT Id FROM Profile WHERE Name='StandardTestUser'];
User pu = new User(Alias='standt',Email='standarduser#testorg.com',LastName='testing',EmailEncodingKey='UTF-8',LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId=p.Id,TimeZoneSidKey='America/New_York',UserName=uniqueUserName);
System.RunAs(pu) {
RestRequest req = new RestRequest();
RestResponse res = new RestResponse();
req.requestURI = '/services/apexrest/sfcheckap/';
req.addParameter('useremail','testuserid#red.com');
req.addParameter('casenumber','00001026');
req.httpMethod = 'GET';
RestContext.request = req;
RestContext.response = res;
System.debug('Current User assigned is: ' + UserInfo.getUserName());
System.debug('Current Profile assigned is: ' + UserInfo.getProfileId());
Test.startTest();
Map<String, Boolean> resultMap = MyRestResource1.doGet();
Test.stopTest();
Boolean debugflag = resultMap.get('accessPermission');
String debugflagstr = String.valueOf(debugflag);
System.assert(debugflagstr.contains('true'));
}
}
}
Found a solution path by using: #isTest(SeeAllData=true)
See article: "Using the isTest(SeeAllData=true) Annotation"
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_seealldata_using.htm
I have a harcoded value in one of my controller
public regions = ['code1','code2']
Now have to read these values from config.groovy file,
I tried to define in config.groovy:-
region = "code1,code2"
in mycontroller :-
def aws = grailsApplication.config.awsRegions;
public awsRegions = aws.split(",")
But it didn't work.
In the Config.groovy you can do:
awsRegions = ['Region 1', 'Region 2']
Then in your Controller you can do:
def awsRegions = grailsApplication.config.awsRegions
Your changes are not working in the comments with Sathish Kumar because you are calling your property "awsRegion" in Config.groovy and accessing it with "grailsApplicatio.config.awsRegions". The keys must match.
1
public regions = ['code1','code2']
should that not be
public List regions = ['code1','code2']
or
public List<String> regions = ['code1','code2']
In the world of groovy / grails public is not required so long as it is not a static variable
2
def aws = grailsApplication.config.awsRegions;
public awsRegions = aws.split(",")
When in doubt :
def aws = grailsApplication.config.awsRegions;
println "aws is ${aws} object class is ${aws.getClass()}"
You should find the println returns [element,e2,e3] within a List already. The getClass() of something tells you what it actually is so you should find it is already a list and does not require the additional split which you would do on a flat string
I have these 2 entities called Owner and Folder.
Every folder(s) belong to an owner.
Inside a folder, we can have subfolder(s), and so on.
Owner Entity
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinColumn(name = "FOLDER_ID", nullable = false)
private Set<Folder> folders = new HashSet<>();
#Column(nullable = false)
private String name;
// Getters and setters
Folder Entity
#ManyToOne
#JoinColumn(name = "PARENT_FOLDER_ID")
private Folder parent;
#OneToMany(cascade = {CascadeType.ALL}, mappedBy = "parent")
private Set<Folder> children = new HashSet<>(); // recursive
#Column(nullable = false)
private String name;
// Getters and setter
An owner named Steve has a folder called mainFolder with a subFolder inside.
When trying to persist the owner, I hit backref issue.
I believe this is due to the subfolder does not know who is its owner.
Question is, since subFolder is inside a mainFolder and mainFolder belongs to Steve, that makes subFolder belongs to Steve as well.
What JPA relationship can I use for this issue?
public static void main(String[] args) {
Folder mainFolder = new Folder();
Folder subFolder = new Folder();
mainFolder.setName("Main Folder");
mainFolder.getChildren().add(subFolder);
subFolder.setName("SubFolder");
subFolder.setParent(mainFolder);
Owner owner = new Owner();
owner.setName("Steve");
owner.getFolders().add(mainFolder);
em.getTransaction().begin();
em.persist(owner); // backrefs error when trying to persist
em.getTransaction().commit();
}
Exception log
Caused by: org.hibernate.PropertyValueException: not-null property references a null or transient value: entity.Folder._foldersBackref
at org.hibernate.engine.Nullability.checkNullability(Nullability.java:72)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:290)
I am using hibernate with H2.
I am able add and save multiple SchoolRef, but am getting the error after retrieving the (ancestor and eagerly fetching the) Education object and then attempting to add another SchoolRef. This was working with SDN 2.0.1, but I've also changed other things, including the Repository/Cypher query below, so I can't isolate it to the upgrade.
#Fetch #RelatedTo(type = "EDUCATION_HAS_SCHOOLREF")
private Set<SchoolRef> schoolRefs = new HashSet<SchoolRef>();
public Education() {
}
public void addSchoolRef(SchoolRef schoolRef) {
getSchoolRefs().add(schoolRef);
}
Repository:
public interface UserRepository extends GraphRepository<User>, CypherDslRepository<User> {
#Query("start id=node:Identifier(identifier={0}) match id<-[:USER_HAS_IDENTIFIER]-user return user")
public User findById(String id);
Stacktrace:
Caused by: java.lang.IllegalArgumentException: Cannot obtain single field value for field 'schoolRef'
at org.springframework.data.neo4j.fieldaccess.RelatedToSingleFieldAccessorFactory$RelatedToSingleFieldAccessor.getValue(RelatedToSingleFieldAccessorFactory.java:94)
at org.springframework.data.neo4j.fieldaccess.DefaultEntityState.getValue(DefaultEntityState.java:97)
at org.springframework.data.neo4j.support.mapping.SourceStateTransmitter.copyEntityStatePropertyValue(SourceStateTransmitter.java:90)
at org.springframework.data.neo4j.support.mapping.SourceStateTransmitter.access$000(SourceStateTransmitter.java:40)
at org.springframework.data.neo4j.support.mapping.SourceStateTransmitter$2.doWithAssociation(SourceStateTransmitter.java:61)
at org.springframework.data.mapping.model.BasicPersistentEntity.doWithAssociations(BasicPersistentEntity.java:207)
at org.springframework.data.neo4j.support.mapping.SourceStateTransmitter.copyPropertiesFrom(SourceStateTransmitter.java:57)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.loadEntity(Neo4jEntityConverterImpl.java:100)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.read(Neo4jEntityConverterImpl.java:92)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister$CachedConverter.read(Neo4jEntityPersister.java:170)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.createEntityFromState(Neo4jEntityPersister.java:189)
at org.springframework.data.neo4j.support.Neo4jTemplate.createEntityFromState(Neo4jTemplate.java:180)
at org.springframework.data.neo4j.fieldaccess.RelationshipHelper.createEntitySetFromRelationshipEndNodes(RelationshipHelper.java:130)
at org.springframework.data.neo4j.fieldaccess.RelatedToFieldAccessor.createEntitySetFromRelationshipEndNodes(RelatedToFieldAccessor.java:86)
at org.springframework.data.neo4j.fieldaccess.RelatedToSingleFieldAccessorFactory$RelatedToSingleFieldAccessor.getValue(RelatedToSingleFieldAccessorFactory.java:76)
at org.springframework.data.neo4j.fieldaccess.DefaultEntityState.getValue(DefaultEntityState.java:97)
at org.springframework.data.neo4j.support.mapping.SourceStateTransmitter.copyEntityStatePropertyValue(SourceStateTransmitter.java:90)
at org.springframework.data.neo4j.support.mapping.SourceStateTransmitter.access$000(SourceStateTransmitter.java:40)
at org.springframework.data.neo4j.support.mapping.SourceStateTransmitter$2.doWithAssociation(SourceStateTransmitter.java:61)
at org.springframework.data.mapping.model.BasicPersistentEntity.doWithAssociations(BasicPersistentEntity.java:207)
at org.springframework.data.neo4j.support.mapping.SourceStateTransmitter.copyPropertiesFrom(SourceStateTransmitter.java:57)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.loadEntity(Neo4jEntityConverterImpl.java:100)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.read(Neo4jEntityConverterImpl.java:92)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister$CachedConverter.read(Neo4jEntityPersister.java:170)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.createEntityFromState(Neo4jEntityPersister.java:189)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.persist(Neo4jEntityPersister.java:244)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.persist(Neo4jEntityPersister.java:231)
at org.springframework.data.neo4j.support.Neo4jTemplate.save(Neo4jTemplate.java:293)
at org.springframework.data.neo4j.support.Neo4jTemplate.save(Neo4jTemplate.java:287)
at org.springframework.data.neo4j.fieldaccess.RelationshipHelper.getOrCreateState(RelationshipHelper.java:119)
at org.springframework.data.neo4j.fieldaccess.RelationshipHelper.createSetOfTargetNodes(RelationshipHelper.java:111)
at org.springframework.data.neo4j.fieldaccess.RelatedToFieldAccessor.createSetOfTargetNodes(RelatedToFieldAccessor.java:82)
at org.springframework.data.neo4j.fieldaccess.RelatedToCollectionFieldAccessorFactory$RelatedToCollectionFieldAccessor.setValue(RelatedToCollectionFieldAccessorFactory.java:66)
at org.springframework.data.neo4j.fieldaccess.ManagedFieldAccessorSet.updateValue(ManagedFieldAccessorSet.java:94)
at org.springframework.data.neo4j.fieldaccess.ManagedFieldAccessorSet.update(ManagedFieldAccessorSet.java:82)
at org.springframework.data.neo4j.fieldaccess.ManagedFieldAccessorSet.add(ManagedFieldAccessorSet.java:108)
---- Edit:
Same error, but under different circumstances..
School school = new School();
school = neo4j.repositoryFor(School.class).save(school);
User user1 = new User("Junit", "1");
SchoolRef schoolRef1 = new SchoolRef();
schoolRef1.setSchool(school);
user1.addSchoolRef(schoolRef1);
user1 = neo4j.repositoryFor(User.class).save(user1);
User user2 = new User("Junit", "2");
SchoolRef schoolRef2 = new SchoolRef();
schoolRef2.setSchool(school);
user2.addSchoolRef(schoolRef2);
user2 = neo4j.repositoryFor(User.class).save(user2); // <- error here
sometimes I can be blind to the obvious problem...
In my case, SchoolRef references a single school, but schools can have many schoolRefs. I had incorrectly implemented School with a single reference back to SchoolRef.
I was able to create multiple SchoolRefs which referenced a single School, but got this error when I tried to fetch a School which had the multiple references.
We ran into this issue as well, but it was due to having a separate relationship with the same label.