Why doesn't createQuery() on the javax.persistence.EntityManager work with upper case attribute? - hibernate-entitymanager

I've encountered a behaviour of javax.persistence.EntityManager I'd like to understand.
I had code similar to the following:
1 // Query Execution
2 EntityManager emext;
3 String query = "SELECT obj FROM MyDatabaseTableBE obj obj.FOO = :fooName)";
4 Query q = emext.createQuery(query);
5 // Corresponding BE
6 ...
7 public static final String FOO = "fOO";
8 ...
9 #AttributeMetadata(attributeNature = AttributeNature.REGULAR)
10 #SearchAttributeMetadata(searchable = false)
11 private String foo;
12 ...
13 public String getFOO() {
14 return foo;
15 }
16 ...
17 public void setFOO(final String foo) {
18 this.foo = foo
19 }
20 ...
throwing the following exception: could not resolve property: fOO of: MyDatabaseTableBE in line 4.
The only thing I changed was the capitalisation:
// Corresponding BE, with changed capitalisation
...
public static final String FOO = "foo";
...
public String getFoo()
...
public void setFoo(final String fOO)
...
And it worked without an exception.
Why did the first version (with the second and third character in uppercase) not work?

Related

Java SE 11 String Final Variable with Ternary Operator Does Not Count as a Constant Variable in Switch Case Expression

I encountered a problem that the following code doesn't work. I ran the code in Java SE 11 (11.0.8), Eclipse 2020-06, Windows 10.
Use String Final Variable with Ternary Operator: Doesn't work
public class Tester {
public static void main(String[] args) {
String switchVar = "abc";
final String caseStr = true ? "abc" : "def";
switch (switchVar) {
case caseStr: System.out.println("Doesn't work");
}
}
}
It has a compile time error: java.lang.Error: Unresolved compilation problem: case expressions must be constant expressions.
However, according to JLS §4.12.4 and JLS §15.28, the String type can be a final variable and ternary operator can also be counted as constant expression.
A constant variable is a final variable of primitive type or type String that is initialized with a constant expression.
A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:
...
The ternary conditional operator ? :
Simple names that refer to constant variables
I did some more tests which showed either one of these points works if not combined together.
Directly use constant expression as case constant: No Problem
public class Tester {
public static void main(String[] args) {
String switchVar = "abc";
switch (switchVar) {
case true ? "abc" : "def": System.out.println("works");
}
}
}
Use String constant variable without ternary operator: No Problem
public class Tester {
public static void main(String[] args) {
String switchVar = "abc";
final String VAR_A = "a";
final String VAR_BC = "bc";
final String CASE = VAR_A + VAR_BC;
switch (switchVar) {
case CASE : System.out.println("works");
}
}
}
Use int with ternary operator instead of String: No Problem
public class Tester {
public static void main(String[] args) {
int switchVar = 10;
final int CASE = 3 > 2 ? 10 : 0;
switch (switchVar) {
case CASE : System.out.println("works");
}
}
}
Could anyone help me please?
With kindly help of others, it is sure now this is a bug of eclipse.
I have reported the bug to eclipse. (Bugzilla – Bug 566332)

How do I call a parseInt method in Main?

I'm currently trying to call 2 parseInt methods from main. One converts characters in a char[] to ints and the other just converts String to int.
But I cant figure out the syntax to have main call them.
I tried parseInt(String conString2); and parseInt(char[] conArray);
I couldnt find anything on google about this either.
public class parseInt
{
public static void main(String[] args)
{
parseInt(String);
parseInt(char[] conArray);
}
public static void parseInt(char[] conArray)
{
System.out.println("Original Charaters 1, 2, 3");
char[] conArrray = {1, 2, 3};
int conInt = Integer.parseInt(new String(conArray));
System.out.println("New ints " + conInt);
}
public static void parseInt(String conString2)
{
String conString = "10";
System.out.println("this number will be converted to int from string " + conString );
int conInt2 = Integer.parseInt(conString);
System.out.println(conInt2);
}
}
Im expecting for it to run those methods but instead it gives the errors "cannot be resolved to variable" on conArray and String. I get "Syntax error, insert ". class" to complete " on the char[].

how to get value generated in mock method

I have a service method in FooService
public void doSomething(){
ArrayList<Foo> fooList = ...;
barService.batchAddFoos(fooList);
List<String> codeList = new ArrayList<>();
for (Foo foo : fooList) {
codeList.add(foo.getCode());
}
String key = "foo_codes";
redisService.sadd(key,codeList.toArray(new String[]{}));
// other code also need use code
}
BarService.batchAddFoos
for (Foo foo : foos) {
foo.setCode(UUID.randomUUID().toString()); // dynamically generate the code value
}
Then I have a unit test to test FooService logic
#Test
public void doSomething() throws Exception {
fooService.doSomething();
ArgumentCaptor<List<Foo>> fooListCaptor = ArgumentCaptor.forClass(List.class);
verify(barService).batchAddFoos(fooListCaptor.capture());
List<Foo> fooList = fooListCaptor.getValue();
Assert.assertNotNull(fooList.get(0).getCode()); // check code value is generated successfully
List<String> codeList = new ArrayList<>();
for (Foo foo : fooList) {
codeList.add(foo.getCode());
}
verify(redisService).sadd("foo_codes",codeList.toArray(new String[]{}));
}
but it is failed, because the code value is null, actually it does not execute any code in BarService.batchAddFoos.I even tried to explicitly populate code value,
fooList.get(0).setCode("aaa");
fooList.get(1).setCode("bbb");
but it is still failed.
Argument(s) are different! Wanted:
redisService.sadd("foo_codes", "aaa", "bbb");
Actual invocation has different arguments:
redisService.sadd("foo_codes", null, null);
Any idea to solve this problem?
Since the fooList is a local variable of the FooService.doSomething, you cannot populate it from the test. Your test will not fail, if assertion will be as following:
Mockito.verify(barService).batchAddFoos(fooListCaptor.capture());
List<Foo> fooList = fooListCaptor.getValue();
//Assert.assertNotNull(fooList.get(0).getCode());
Assert.assertFalse(fooList.isEmpty());
...
If you will initialize the code in the Foo constructor with Strings.EMPTY or any other not null value, your original assertion will work.
As such scenario, could populate some properties of some object parameters as you like, e.g.
doAnswer(new Answer() {
#Override
public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
List<Foo> fooList = invocationOnMock.getArgumentAt(0, List.class);
fooList.get(0).setCode("aaa"); // explicitly specify the first foo object have code of "aaa"
fooList.get(1).setCode("bbb"); // explicitly specify the second foo object have code of "bbb"
return null;
}
}).when(barService).batchAddFoos(anyList());

Are accessors / mutators auto-defined in Groovy?

In the section on handling Java Beans with Groovy of Groovy In Action, I found this script (slightly modified):
class Book{
String title
}
def groovyBook = new Book()
// explicit way
groovyBook.setTitle('What the heck, really ?')
println groovyBook.getTitle()
// short-hand way
groovyBook.title = 'I am so confused'
println groovyBook.title
There are no such methods in the class Book so how does that work ?
Yes, they are auto defined and calling book.title is actually calling book.getTitle()
See http://groovy.codehaus.org/Groovy+Beans
You can see this in action with the following script:
def debug( clazz ) {
println '----'
clazz.metaClass.methods.findAll { it.name.endsWith( 'Name' ) || it.name.endsWith( 'Age' ) }.each { println it }
}
class A {
String name
int age
}
debug( A )
// Prints
// public int A.getAge()
// public java.lang.String A.getName()
// public void A.setAge(int)
// public void A.setName(java.lang.String)
// Make name final
class B {
final String name
int age
}
debug( B )
// Prints
// public int B.getAge()
// public java.lang.String B.getName()
// public void B.setAge(int)
// Make name private
class C {
private String name
int age
}
debug( C )
// Prints
// public int C.getAge()
// public void C.setAge(int)
// Try protected
class D {
protected String name
int age
}
debug( D )
// Prints
// public int D.getAge()
// public void D.setAge(int)
// And public?
class E {
public String name
int age
}
debug( E )
// Prints
// public int E.getAge()
// public void E.setAge(int)
Several notes:
For all property fields(public ones only), there are autogenerated accesors.
Default visibility is public. So, you should use private/protected keyword to restrict accessor generation.
Inside an accessor there is direct field access. like this.#title
Inside a constructor you have direct access to! This may be unexpected.
For boolean values there are two getters with is and get prefixes.
Each method with such prefixes, even java ones are treated as accessor, and can be referenced in groovy using short syntax.
But sometimes, if you have ambiguous call there may be class cast exception.
Example code for 4-th point.
class A{
private int i = 0;
A(){
i = 4
println("Constructor has direct access. i = $i")
}
void setI(int val) { i = val; println("i is set to $i"); }
int getI(){i}
}
def a = new A() // Constructor has direct access. i = 4
a.i = 5 // i is set to 5
println a.i // 5
​
4-th note is important, if you have some logic in accessor, and want it to be applied every time you call it. So in constructor you should explicit call setI() method!
Example for 7
class A{
private int i = 0;
void setI(String val) { println("String version.")}
void setI(int val) { i = val; println("i is set to $i"); }
}
def a = new A()
a.i = 5 // i is set to 5
a.i = "1s5" // GroovyCastException: Cannot cast object '1s5' with class 'java.lang.String' to class 'int'
​
So, as I see property-like access uses first declared accessor, and don't support overloading. Maybe will be fixed later.
Groovy generates public accessor / mutator methods for fields when and only when there is no access modifier present. For fields declared as public, private or protected no getters and setters will be created.
For fields declared as final only accessors will be created.
All that applies for static fields analogously.

Optional Parameter in Unittest

I would like to test a method with optional Parameters in MSTest.
private CalcSomthing(double valueone, double valuetwo = 10)
{
// Do somthing
}
When i call this method it works fine. But wen i run it in Unittest (MSTest) the Valuetwo wouldn't initialize with value 10.
Are MSTest unable to test optional Parameter or i'm wrong?
[TestMethod]
public void CalcSomthingTest()
{
var someclass= new Someclass_Accessor();
someclass.CalcSomthing(10);
}
The result is: Valueone = 10 and ValueTwo = 0.0;
This test passes in Visual Studio 2010:
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TestProject1
{
public class Someclass
{
public double CalcSomthing(double valueone, double valuetwo = 10)
{
Assert.IsTrue(valuetwo == 10);
return valueone + valuetwo;
}
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void CalcSomthingTest()
{
var someclass = new Someclass();
someclass.CalcSomthing(10);
}
}
}
in either ReSharper or TestRunner:
------ Test started: Assembly: TestProject1.dll ------
1 passed, 0 failed, 0 skipped, took 1.14 seconds (MSTest 10.0).
Agreed its a problem.
Make the method above private and then SomeClass_Accessor is generated, the read-only metadata for which exposes the signature
public double CalcSomthing(double valueone, double valuetwo = null)
The code works fine but the test fails
Any solutions ?

Resources