Storing null values inside ArrayList and Set - arraylist

class Employee
{
int id;
Employee(int id)
{
this.id = id;
}
public int getID()
{
return id;
}
public void displayID()
{
System.out.println("ID="+id);
}
}
public class Example
{
public static void main(String[] args)
{
Employee employee1 = new Employee(100);
Employee employee3 = null;
List<Employee> arrayListEx = new ArrayList<Employee>();
Set<Employee> setEx = new HashSet<Employee>();
arrayListEx.add(employee1);
arrayListEx.add(employee3);
setEx.add(employee1);
setEx.add(employee3);
}
}
Friends,
As per my understanding Set should not allow null values to get added to it.
Should the above code snippet throw compile time error for "setEx.add(employee3)" ?
Please advice, Thanks in advance.

From the Java Hashset documentation: "This class permits the null element". The file will compile.
You mentioned you believe that Set doesn't allow nulls. This depends on its implementation (link to docs)

Related

#Transactional doesn't update records using HQL or SQL

I am using transactional annotation in order to enable auto-commit in Oracle DB.
When I use criteria to update records, I get the record updated successfully. But when I use HQL or SQL, in the console the query is printed but doesn't execute
This is Notification DAO
#Repository("SystemUserNotificationDao")
public class SystemUserNotificationDaoImpl extends AbstractDao<BigDecimal, SystemUserNotification> implements SystemUserNotificationDao {
#Override
public Number setNotificationsAsSeen() {
Query query = createHqlQuery("update SystemUserNotification set seen = 1 where seen = 0");
return (Number)query.executeUpdate();
}
}
This is the service
Service("SystemUserNotificationService")
#Transactional
public class SystemUserNotificationServiceImpl implements SystemUserNotificationService {
#Autowired
SystemUserNotificationDao systemUserNotificationDao;
#Override
public Number setNotificationsAsSeen() {
return systemUserNotificationDao.setNotificationsAsSeen();
}
}
This is the AbstractDao
public abstract class AbstractDao<PK extends Serializable, T> {
private final Class<T> persistentClass;
#SuppressWarnings("unchecked")
public AbstractDao() {
this.persistentClass = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
}
#Autowired
private SessionFactory sessionFactory;
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
#SuppressWarnings("unchecked")
public T getByKey(PK key) {
return (T) getSession().get(persistentClass, key);
}
public void persist(T entity) {
getSession().persist(entity);
}
public void update(T entity) {
getSession().update(entity);
}
public void saveOrUpdate(T entity) {
getSession().saveOrUpdate(entity);
}
public void delete(T entity) {
getSession().delete(entity);
}
protected Criteria createEntityCriteria() {
return getSession().createCriteria(persistentClass);
}
protected SQLQuery createSqlQuery(String query) {
return getSession().createSQLQuery(query);
}
protected Query createHqlQuery(String query) {
return getSession().createQuery(query);
}
}
I tried to add transaction.begin and commit but it gives me nested transactions not supported
#Override
public Number setNotificationsAsSeen() {
// Query query = createHqlQuery("update SystemUserNotification set seen = 1 where seen = 0");
Transaction tx = getSession().beginTransaction();
Query query = getSession().createQuery("update SystemUserNotification set seen = 1 where seen = 0");
Number n = (Number)query.executeUpdate();
tx.commit();
return n;
}
The issue was with SQL developer tool. there were uncommitted changes, I closed the dev tool and the update query worked fine

Mapping DTO with final members in MapStruct

is there a way to map a DTO using MatStruct which have a few final data members as well and cannot have a default constructor , like :
public class TestDto {
private final String testName;
private int id;
private String testCase;
public TestDto(String testName) {
this.testName = testName;
}
public String getTestName() {
return testName;
}
public int getId() {
return id;
}
public String getTestCase() {
return testCase;
}
public void setId(int id) {
this.id = id;
}
public void setTestCase(String testCase) {
this.testCase = testCase;
}
}
please suggest how could this DTO be mapped using MapStruct.
You can use #ObjectFactory that would construct an instance of your DTO.
For example:
#Mapper
public interface MyMapper {
#ObjectFactory
default TestDto create() {
return new TestDto("My Test Name");
}
//the rest of the mappings
}
You can also enhance the #ObjectFactory to accept the source parameter, that you can use to construct the TestDto. You can even use a #Context as an Object Factory.
NB: You don't have to put the #ObjectFactory method in the same Mapper, or even a MapStruct #Mapper. You can put it in any class (or make it static) and then #Mapper(uses = MyFactory.class)

No converter found capable of converting from type [java.lang.String] to type [org.springframework.data.solr.core.geo.Point]

I am trying to use spring-data-solr in order to access to my Solr instance through my Spring boot application. I have the following bean class:
#SolrDocument(solrCoreName = "associations")
public class Association implements PlusimpleEntityI {
#Id
#Indexed
private String id;
#Indexed
private String name;
#Indexed
private Point location;
#Indexed
private String description;
#Indexed
private Set<String> tags;
#Indexed
private Set<String> topics;
#Indexed
private Set<String> professionals;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Point getLocation() {
return location;
}
public void setLocation(Point location) {
this.location = location;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<String> getTags() {
return tags;
}
public void setTags(Set<String> tags) {
this.tags = tags;
}
public Set<String> getTopics() {
return topics;
}
public void setTopics(Set<String> topics) {
this.topics = topics;
}
public Set<String> getProfessionals() {
return professionals;
}
public void setProfessionals(Set<String> professionals) {
this.professionals = professionals;
}
}
I have implemented the following repository in order to access to the related information:
public interface AssociationsRepository extends SolrCrudRepository<Association, String> {
}
I have created a configuration class which looks like the following one:
#Configuration
#EnableSolrRepositories(basePackages = {"com.package.repositories"}, multicoreSupport = true)
public class SolrRepositoryConfig {
#Value("${solr.url}")
private String solrHost;
#Bean
public SolrConverter solrConverter() {
MappingSolrConverter solrConverter = new MappingSolrConverter(new SimpleSolrMappingContext());
solrConverter.setCustomConversions(new CustomConversions(null));
return solrConverter;
}
#Bean
public SolrClientFactory solrClientFactory () throws Exception {
return new MulticoreSolrClientFactory(solrClient());
}
#Bean
public SolrClient solrClient() throws Exception {
return new HttpSolrClient.Builder(solrHost).build();
}
#Bean
public SolrOperations associationsTemplate() throws Exception {
SolrTemplate solrTemplate = new SolrTemplate(solrClient());
solrTemplate.setSolrConverter(solrConverter());
return solrTemplate;
}
}
Unfortunately, when I try to read an association from my Solr instance I got the following error:
org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [org.springframework.data.solr.core.geo.Point]
I don't understand why it is not able to find a converter if I have explicitly defined it in the solrTemplate() method.
This is my POM definition:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-solr</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
Thank you for your help.
EDIT:
I've also tried with different BUILD-RELEASEs but they are highly unstable and I've found a lot of errors using them.
Alessandro, as you can see directly in the GeoConverters class on GitHub, the implemented converters are only for:
org.springframework.data.geo.Point
and not for:
org.springframework.data.solr.core.geo.Point
Simply use this class and you don't even need a custom converter for this. Spring Data for Solr will perform the conversion for you.
I'm using a slightly patched version of the 3.0.0 M4, but I'm pretty sure this solution should apply seamlessly also to your case.

Glassfish - cannot remove entity using JPA

In my exploration of JPA, I have the code below (which I understand should not be used in production). Running my code produces the following error:
java.lang.IllegalStateException:
Exception Description: Cannot use an EntityTransaction while using JTA.
The Resource code is as follows:
#Path("users")
public class UsersAPI {
#Context
UriInfo uriInfo;
#Inject
UserBean accountsBean;
#GET
#Path("deduplicate")
public Response deduplicateDB(){
List<UserProfile> profiles = accountsBean.getAll();
int profilesNum = profiles.size();
for(int i = 0; i < profilesNum; ++i){
for(int k = 0; k < profilesNum; ++k){
if(i != k){ //if it's not the same profile
if(profiles.get(i).getUsername().equals(profiles.get(k).getUsername())){
accountsBean.remove(profiles.get(k));
profiles.remove(k);
}
}
profilesNum = profiles.size();
}
}
return Response.ok().build();
}
}
The code in the ProfilesBean is as follows:
#Local
#Stateless
public class UserBean {
#PersistenceContext
EntityManager eManager;
public void save(UserProfile data){
eManager.merge(data);
}
public void remove(UserProfile data){
eManager.getTransaction().begin();
eManager.remove(data);
eManager.getTransaction().commit();
}
public List<UserProfile> getAll(){
Query q = eManager.createQuery("SELECT profile FROM Users profile");
return (List<UserProfile>)q.getResultList();
}
}
Here is the code for the Entity class:
#Entity(name="Users")
public class UserProfile {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
Long id;
String password;
#Column(unique=true)
String username;
public UserProfile(String username){
setUsername(username);
}
public UserProfile(){
this(null);
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
It seems like the error comes from my misusing the platform somehow. How can I fix this code and not misuse the platform in the future?
If you are using JTA as transaction-type in persistence.xml file just leave JTA handles your transactions
public void remove(UserProfile data){
eManager.remove(eManager.merge(data));
}
UPDATE:
In a more clear solution you could use "find", but you need to provide the object id
public void remove(UserProfile data){
UserProfile e = em.find(UserProfile.class, data.getId());
eManager.remove(e);
}

Arraylist can't add element

Why isn't this working for me?
public class Band {
public void addMember(Musician musician) {
musicians.add(musician);
System.out.println("Muscian: " + musician + "was successfully added");
}
}
public static void main(String[] args) {
Band Beatles = new Band("Beatles");
Beatles.addMember("John Lennon");
}
public class Musician {
private String name;
public Musician(String name, Instrument instrument) {
this.name = name;
Instrument Guitar = instrument;
}
public void play() {
}
}
Beatles.addMember("John Lennon");
should be
Beatles.addMember(new Musician("John Lennon", new Instrument(new Guitar()));
I suspect, without seeing your actual Instrument class, based on your comment that this line should work.
The problem is that you are treating some objects as Strings. You need to create the object out of the class that defines it first.