Exception when adding a Role from DTO to Entity










0















Faced with an incomprehensible problem for me: when I try to add a user role, the system jumps into reflection and throws out NullPointerException, instead of taking the Role value from DAO.



Entity:



@Entity
@Table(name = "users")
public class User implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@Column(name = "email", unique = true, nullable = false)
private String email;

@Column(name = "password", nullable = false)
private String password;

@Column(name = "first_name", length = 50, nullable = false)
private String firstName;

@Column(name = "last_name", length = 50, nullable = false)
private String lastName;

@Temporal(TemporalType.DATE)
@DateTimeFormat(pattern = "yyyy-MM-dd")
@Column(name = "birth_date", nullable = false)
private Date birthDate;

@ManyToOne
@JoinColumn(name = "role")
private Role role;

// getter & setter


and



@Entity
@Table(name = "roles")
public class Role implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@Column(name = "name")
private String name;

@OneToMany(mappedBy = "role")
private Set<User> users;

// getter & setter


DAO (role):



@Repository
public class RoleDaoImpl extends AbstractGenericDao<Role> implements RoleDao

private static final Logger LOG = Logger.getLogger(RoleDaoImpl.class.getName());

private static final String GET_ROLE_BY_NAME = "SELECT r FROM Role r WHERE r.name = :name";

@Override
public Role getRoleByName(String name)
Query query = getCurrentSession().createQuery(GET_ROLE_BY_NAME);
query.setParameter("name", name);

Role role = null;
try
role = (Role) query.getSingleResult();
catch (Exception e)
LOG.warn(e);

return role;





Now I am trying to convert my userDto (it repeats entities, but does not contain id and role). Everything works until I try to add a user.addRole:



 public static User constructUser(UserDto userDto) 
User user = new User();
user.setEmail(userDto.getEmail());
user.setPassword(userDto.getPassword());
user.setFirstName(userDto.getFirstName());
user.setLastName(userDto.getLastName());
user.setBirthDate(DateConverter.convertDate(userDto.getBirthDate()));
//user.setRole(roleDao.getRoleByName("ROLE_USER"));
return user;



As soon as it comes to the commented line, the compiler does not enter the DAO, it goes into reflection and tries to do something there, and returns NullPointer.



Tell the inexperienced what could be the case and how to fix it. All this has a headache.



Tables exist, values are valid. Without an DTO (through an entity) everything works fine.










share|improve this question

















  • 1





    Well, while I was writing a post, I think I understood what was the matter. I'm trying to work with a database without an @ transaction, and apparently, therefore, the case does not work. A few hours for the obvious thing. Transferred the addition of a role to another place. Thanks to all!

    – Vincent G
    Nov 14 '18 at 23:30
















0















Faced with an incomprehensible problem for me: when I try to add a user role, the system jumps into reflection and throws out NullPointerException, instead of taking the Role value from DAO.



Entity:



@Entity
@Table(name = "users")
public class User implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@Column(name = "email", unique = true, nullable = false)
private String email;

@Column(name = "password", nullable = false)
private String password;

@Column(name = "first_name", length = 50, nullable = false)
private String firstName;

@Column(name = "last_name", length = 50, nullable = false)
private String lastName;

@Temporal(TemporalType.DATE)
@DateTimeFormat(pattern = "yyyy-MM-dd")
@Column(name = "birth_date", nullable = false)
private Date birthDate;

@ManyToOne
@JoinColumn(name = "role")
private Role role;

// getter & setter


and



@Entity
@Table(name = "roles")
public class Role implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@Column(name = "name")
private String name;

@OneToMany(mappedBy = "role")
private Set<User> users;

// getter & setter


DAO (role):



@Repository
public class RoleDaoImpl extends AbstractGenericDao<Role> implements RoleDao

private static final Logger LOG = Logger.getLogger(RoleDaoImpl.class.getName());

private static final String GET_ROLE_BY_NAME = "SELECT r FROM Role r WHERE r.name = :name";

@Override
public Role getRoleByName(String name)
Query query = getCurrentSession().createQuery(GET_ROLE_BY_NAME);
query.setParameter("name", name);

Role role = null;
try
role = (Role) query.getSingleResult();
catch (Exception e)
LOG.warn(e);

return role;





Now I am trying to convert my userDto (it repeats entities, but does not contain id and role). Everything works until I try to add a user.addRole:



 public static User constructUser(UserDto userDto) 
User user = new User();
user.setEmail(userDto.getEmail());
user.setPassword(userDto.getPassword());
user.setFirstName(userDto.getFirstName());
user.setLastName(userDto.getLastName());
user.setBirthDate(DateConverter.convertDate(userDto.getBirthDate()));
//user.setRole(roleDao.getRoleByName("ROLE_USER"));
return user;



As soon as it comes to the commented line, the compiler does not enter the DAO, it goes into reflection and tries to do something there, and returns NullPointer.



Tell the inexperienced what could be the case and how to fix it. All this has a headache.



Tables exist, values are valid. Without an DTO (through an entity) everything works fine.










share|improve this question

















  • 1





    Well, while I was writing a post, I think I understood what was the matter. I'm trying to work with a database without an @ transaction, and apparently, therefore, the case does not work. A few hours for the obvious thing. Transferred the addition of a role to another place. Thanks to all!

    – Vincent G
    Nov 14 '18 at 23:30














0












0








0








Faced with an incomprehensible problem for me: when I try to add a user role, the system jumps into reflection and throws out NullPointerException, instead of taking the Role value from DAO.



Entity:



@Entity
@Table(name = "users")
public class User implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@Column(name = "email", unique = true, nullable = false)
private String email;

@Column(name = "password", nullable = false)
private String password;

@Column(name = "first_name", length = 50, nullable = false)
private String firstName;

@Column(name = "last_name", length = 50, nullable = false)
private String lastName;

@Temporal(TemporalType.DATE)
@DateTimeFormat(pattern = "yyyy-MM-dd")
@Column(name = "birth_date", nullable = false)
private Date birthDate;

@ManyToOne
@JoinColumn(name = "role")
private Role role;

// getter & setter


and



@Entity
@Table(name = "roles")
public class Role implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@Column(name = "name")
private String name;

@OneToMany(mappedBy = "role")
private Set<User> users;

// getter & setter


DAO (role):



@Repository
public class RoleDaoImpl extends AbstractGenericDao<Role> implements RoleDao

private static final Logger LOG = Logger.getLogger(RoleDaoImpl.class.getName());

private static final String GET_ROLE_BY_NAME = "SELECT r FROM Role r WHERE r.name = :name";

@Override
public Role getRoleByName(String name)
Query query = getCurrentSession().createQuery(GET_ROLE_BY_NAME);
query.setParameter("name", name);

Role role = null;
try
role = (Role) query.getSingleResult();
catch (Exception e)
LOG.warn(e);

return role;





Now I am trying to convert my userDto (it repeats entities, but does not contain id and role). Everything works until I try to add a user.addRole:



 public static User constructUser(UserDto userDto) 
User user = new User();
user.setEmail(userDto.getEmail());
user.setPassword(userDto.getPassword());
user.setFirstName(userDto.getFirstName());
user.setLastName(userDto.getLastName());
user.setBirthDate(DateConverter.convertDate(userDto.getBirthDate()));
//user.setRole(roleDao.getRoleByName("ROLE_USER"));
return user;



As soon as it comes to the commented line, the compiler does not enter the DAO, it goes into reflection and tries to do something there, and returns NullPointer.



Tell the inexperienced what could be the case and how to fix it. All this has a headache.



Tables exist, values are valid. Without an DTO (through an entity) everything works fine.










share|improve this question














Faced with an incomprehensible problem for me: when I try to add a user role, the system jumps into reflection and throws out NullPointerException, instead of taking the Role value from DAO.



Entity:



@Entity
@Table(name = "users")
public class User implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@Column(name = "email", unique = true, nullable = false)
private String email;

@Column(name = "password", nullable = false)
private String password;

@Column(name = "first_name", length = 50, nullable = false)
private String firstName;

@Column(name = "last_name", length = 50, nullable = false)
private String lastName;

@Temporal(TemporalType.DATE)
@DateTimeFormat(pattern = "yyyy-MM-dd")
@Column(name = "birth_date", nullable = false)
private Date birthDate;

@ManyToOne
@JoinColumn(name = "role")
private Role role;

// getter & setter


and



@Entity
@Table(name = "roles")
public class Role implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@Column(name = "name")
private String name;

@OneToMany(mappedBy = "role")
private Set<User> users;

// getter & setter


DAO (role):



@Repository
public class RoleDaoImpl extends AbstractGenericDao<Role> implements RoleDao

private static final Logger LOG = Logger.getLogger(RoleDaoImpl.class.getName());

private static final String GET_ROLE_BY_NAME = "SELECT r FROM Role r WHERE r.name = :name";

@Override
public Role getRoleByName(String name)
Query query = getCurrentSession().createQuery(GET_ROLE_BY_NAME);
query.setParameter("name", name);

Role role = null;
try
role = (Role) query.getSingleResult();
catch (Exception e)
LOG.warn(e);

return role;





Now I am trying to convert my userDto (it repeats entities, but does not contain id and role). Everything works until I try to add a user.addRole:



 public static User constructUser(UserDto userDto) 
User user = new User();
user.setEmail(userDto.getEmail());
user.setPassword(userDto.getPassword());
user.setFirstName(userDto.getFirstName());
user.setLastName(userDto.getLastName());
user.setBirthDate(DateConverter.convertDate(userDto.getBirthDate()));
//user.setRole(roleDao.getRoleByName("ROLE_USER"));
return user;



As soon as it comes to the commented line, the compiler does not enter the DAO, it goes into reflection and tries to do something there, and returns NullPointer.



Tell the inexperienced what could be the case and how to fix it. All this has a headache.



Tables exist, values are valid. Without an DTO (through an entity) everything works fine.







spring hibernate spring-security dto






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 14 '18 at 23:25









Vincent GVincent G

11




11







  • 1





    Well, while I was writing a post, I think I understood what was the matter. I'm trying to work with a database without an @ transaction, and apparently, therefore, the case does not work. A few hours for the obvious thing. Transferred the addition of a role to another place. Thanks to all!

    – Vincent G
    Nov 14 '18 at 23:30













  • 1





    Well, while I was writing a post, I think I understood what was the matter. I'm trying to work with a database without an @ transaction, and apparently, therefore, the case does not work. A few hours for the obvious thing. Transferred the addition of a role to another place. Thanks to all!

    – Vincent G
    Nov 14 '18 at 23:30








1




1





Well, while I was writing a post, I think I understood what was the matter. I'm trying to work with a database without an @ transaction, and apparently, therefore, the case does not work. A few hours for the obvious thing. Transferred the addition of a role to another place. Thanks to all!

– Vincent G
Nov 14 '18 at 23:30






Well, while I was writing a post, I think I understood what was the matter. I'm trying to work with a database without an @ transaction, and apparently, therefore, the case does not work. A few hours for the obvious thing. Transferred the addition of a role to another place. Thanks to all!

– Vincent G
Nov 14 '18 at 23:30













0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53310277%2fexception-when-adding-a-role-from-dto-to-entity%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53310277%2fexception-when-adding-a-role-from-dto-to-entity%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

Barbados

How to read a connectionString WITH PROVIDER in .NET Core?

Node.js Script on GitHub Pages or Amazon S3