Address value shows null - java

I have two classes Student and Address which implements IStudent ans IAddress interfaces respectively. Student class has a relationship with Address class. That is why i have declared a reference member of it.
public class Student implements IStudent {
private String code;
private String name;
#Autowired
private IAddress address;
#Override
public String getCode() {
return this.code;
}
#Override
public String getName() {
return this.name;
}
public void setCode(String code) {
this.code = code;
}
public void setName(String name) {
this.name = name;
}
public IAddress getAddress() {
return this.address;
}
public void setAddress(Address address) {
this.address = address;
}
}
and I have Address class
public class Address implements IAddress{
private String city;
private String pinCode;
private String houseNo;
private String roadName;
#Override
public String getCity() {
return this.city;
}
#Override
public String getPinCode() {
return this.pinCode;
}
#Override
public String getHouseNo() {
return this.houseNo;
}
#Override
public String getRoadName() {
return this.roadName;
}
public void setCity(String city) {
this.city = city;
}
public void setPinCode(String pinCode) {
this.pinCode = pinCode;
}
public void setHouseNo(String houseNo) {
this.houseNo = houseNo;
}
public void setRoadName(String roadName) {
this.roadName = roadName;
}
}
In my applicationContext.xml file i have written the following bean definitions
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<bean id="studentbean" class="main.Student">
<property name="code" value="S001"></property>
<property name="name" value="Subhabrata Mondal"></property>
</bean>
<bean id="addressbean" class="main.Address">
<property name="houseNo" value="119/2"></property>
<property name="roadName" value="South Avenue"></property>
<property name="city" value="Delhi"></property>
<property name="pinCode" value="110005"></property>
</bean>
</beans>
When i have checked Student object after initialization of bean, name and code has assigned with setter method. But the address is not assigned. Thus it shows null value for address. I have marked address with #Autowired annotation. Can you please help?
ApplicationContext factory = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = (Student) factory.getBean("studentbean");
System.out.println(student.getAddress());

you need to explicitly wire to Address not IAddress since the CI only knows Address, if you want to wired
#Autowired
private Address address;
or you need to define a bean with type IAddress but make sure you do not have more than implementation or spring will get confused, if you have more than one implementation use can qualifiers to clear the ambiguity

This whole example is kind of strange but you can get rid of the #Autowired annotation and use following bean configuration instead;
<bean id="studentbean" class="main.Student">
<property name="code" value="S001"></property>
<property name="name" value="Subhabrata Mondal"></property>
<property name="address" >
<ref local="addressbean"/>
</property>
</bean>

Related

Invalid property 'name' of bean class [Country]: Bean property 'name' is not writable or has an invalid setter method. Did you mean 'cname'?

I am new to springs, so I was just trying to implement inheritance in spring.
Customer.java
public class Customer {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Country.java
public class Country {
String cname;
String city;
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Main.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String args[]){
ApplicationContext context = new ClassPathXmlApplicationContext("Bean1.xml");
Customer cus = (Customer) context.getBean("customer");
System.out.println(cus.getName());
Country con = (Country) context.getBean("country");
System.out.println(con.getCname());
}
}
Bean1.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id = "customer" class = "Customer">
<property name = "name" value = "Garima"/>
</bean>
<bean id ="country" class="Country" parent="customer">
<property name = "cname" value = "India"/>
<property name = "city" value = "Delhi"/>
</bean>
</beans>
Every time I run this without parent in Bean1.xml, this is running fine. As soon as I add parent , I receive the below mentioned error.
Error : Invalid property name of bean class [Country]: Bean property name is not writable or has an invalid setter method. Did you mean cname?
I have noticed this case with many other examples as well.
Can someone please help me with this?
This is because your bean definition suggests that Customer is parent of Country but your class Country doesn't extend Customer
<bean id ="country" class="Country" parent="customer">
So you have two options
Either remove parent="customer" from your bean definition
OR Extend Customer in Country class like
public class Country extends Customer{...

Perform two save("entity-name",object) in a single session of hibernate?

I have a POJO class NewUniversity.java. I've created a mapping file for it viz. RegisterAction.hbm.xml. Now the problem is when I try to call the save methods from DAO class, only the first one gets executed, the second one doesn't. I've two tables linked to one entity through 'entity-mapping' attribute in the xml file.
File: NewUniversity.java
public class NewUniversity implements Serializable {
// University fields
private String uCode;
private String uName;
private String uAddress;
private String uCity;
private String uState;
private long uContactNo;
private String uEmail;
// University director fields
private String name;
private String address;
private String city;
private String state;
private long contactNo;
private String email;
private String userName;
private String pwd;
public String getuCode() {
return uCode;
}
public void setuCode(String uCode) {
this.uCode = uCode;
}
public String getuName() {
return uName;
}
public void setuName(String uName) {
this.uName = uName;
}
public String getuAddress() {
return uAddress;
}
public void setuAddress(String uAddress) {
this.uAddress = uAddress;
}
public String getuCity() {
return uCity;
}
public void setuCity(String uCity) {
this.uCity = uCity;
}
public String getuState() {
return uState;
}
public void setuState(String uState) {
this.uState = uState;
}
public long getuContactNo() {
return uContactNo;
}
public void setuContactNo(long uContactNo) {
this.uContactNo = uContactNo;
}
public String getuEmail() {
return uEmail;
}
public void setuEmail(String uEmail) {
this.uEmail = uEmail;
}
// University directors setters/getters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public long getContactNo() {
return contactNo;
}
public void setContactNo(long contactNo) {
this.contactNo = contactNo;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
File: RegisterAction.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="in.ryr.register.NewUniversity" table="university"
entity-name="university">
<id name="uCode" column="code" type="string">
<generator class="assigned" />
</id>
<property name="uName" column="name" />
<property name="uAddress" column="address" />
<property name="uCity" column="city" />
<property name="uState" column="state" />
<property name="uContactNo" column="contact_no" />
<property name="uEmail" column="email" />
<property name="userName" column="username" />
</class>
<class name="in.ryr.register.NewUniversity" table="university_director"
entity-name="uniDirector">
<id name="userName" column="username" type="string">
<generator class="assigned" />
</id>
<property name="name" column="name" />
<property name="address" column="address" />
<property name="city" column="city" />
<property name="state" column="state" />
<property name="contactNo" column="contact_no" />
<property name="email" column="email" />
<property name="pwd" column="password" />
<property name="uCode" column="u_code" />
</class>
</hibernate-mapping>
File: RegisterDAO.java
public void register(NewUniversity user) throws Exception {
session = factory.openSession();
transaction = session.beginTransaction();
try {
session.save("university", user); //This is working fine
session.save("uniDirector", user); //This doesn't execute at all
transaction.commit();
session.close();
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
session.close();
}
}
I've tried using persist() as well. But no luck!
The point is, when I perform it on two different sessions, it works perfectly. (All the objects value are coming through .jsp to struts). For some reasons I didn't use annotations.
Maybe it is because Session#save(entityName, object) method requires object to be a "transient" object (i.e. that has not already been persisted), and that, after the first call to session.save("university", user); then user is no more transient.
Persist the given transient instance, first assigning a generated
identifier. (Or using the current value of the identifier property if
the assigned generator is used.) This operation cascades to associated
instances if the association is mapped with cascade="save-update"
What happens when you make a get of your persisted "university" entity just after the first save, and then save it as "uniDirector" ?

No constructor with 3 arguments defined in class?

Let me clear it, I'm a completely beginner in Spring framework.
I've three class files, Now i'm getting an error into beans.xml. You could take a look into my codes.
Here is MyAddress.java:
package com.project;
public class MyAddress {
private String city;
private String state;
private String address;
public void Address(String city, String state, String address){
this.city=city;
this.state=state;
this.address=address;
}
public String toString(){
return city+" "+state+" "+address;
}
}
Here is my Employee.java
package com.project;
public class Employee {
private int id;
private String name;
private MyAddress address;
public Employee(){
System.out.print("Default constructor..");
}
public void Employee(int id, String name, MyAddress address){
this.id=id;
this.name=name;
this.address=address;
}
public void show(){
System.out.println(id+" "+name);
System.out.println(address.toString());
}
}
Here is my MainProgram.java
package com.project;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainProgram {
public static void main(String[] args){
ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");
Employee em=(Employee)ac.getBean("e");
em.show();
}
}
and finally here is my beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="e" class="com.project.MyAddress">
<constructor-arg value="USA" type="String"></constructor-arg>
<constructor-arg value="Delhi" type="String"></constructor-arg>
<constructor-arg value="Bangalore" type="String"></constructor-arg>
</bean>
<bean id="e2" class="com.project.Employee">
<constructor-arg value="123" type="int"></constructor-arg>
<constructor-arg value="raj"></constructor-arg>
<constructor-arg>
<ref bean="e"/>
</constructor-arg>
</bean>
</beans>
I'm getting an error in beans.xml files as No constructor with 3 arguments defined in class
PLease help, what's that mean?
Surely, help would be appreciated!!
This
public void Address(String city, String state, String address)
should be
public MyAddress(String city, String state, String address)
You got the class name wrong in your constructor, and in addition, constructors don't have a return type.
You have a similar error for Employee :
public void Employee(int id, String name, MyAddress address)
should be
public Employee(int id, String name, MyAddress address)
As defined here,
"A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type"
In the MyAddress class instead of creating a constructor you created a Address method,
changing public void Address(...) to public MyAddress(...) will make it work
The address class has a default constructor. Omit void keyword from method.

Adding properties for a bean

I have following bean class. I want to define this bean into the xml file.
I want to know which objects of this bean are added as a property of the bean in the xml?
public class Mybean{
public String name;
public String address;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name=name;
}
public String getAddress()
{
return address;
}
}
Since you have getters and setters for the name and address fields they can both serve as properties.
<bean id="mybean" class="package.to.MyBean">
<property name="name" value="something"/>
<property name="address" value="something"/>
</bean>
Reference: http://www.springbyexample.org/examples/intro-to-ioc-basic-setter-injection.html
Let your class implement InitializingBean, then in the afterPropertiesSet() method, you can check which property has been set by spring

I am getting NullPointer Excpetion how to resolve it.I am using Spring 3.0 and jdbcTemplate

//here I define all classes and interface which i used
//Service interface
public interface CustomerService {
public void addCustomer(CustomerTO cto);
}
//Service class implementation
public class CustomerServiceImpl implements CustomerService {
#Autowired
CustomerDAO cdao=null;
public void addCustomer(CustomerTO cto){
cdao.addCustomer(cto);
}
}
//CustomerTO Class
public class CustomerTO {
private int cid;
private String cname;
private String email;
private long phone;
private String city;
public CustomerTO(int cid, String cname, String email, long phone,
String city) {
this.cid = cid;
this.cname = cname;
this.email = email;
this.phone = phone;
this.city = city;
}
//Setter and Getters
public class JdbcCustomerDAO implements CustomerDAO {
#Autowired
JdbcTemplate jdbcTemp;
public void addCustomer(CustomerTO cto){
String sql="insert into customer values(?,?,?,?,?)";
Object ar[]={cto.getCid(),cto.getCname(),cto.getEmail(),cto.getPhone(),cto.getCity()};
jdbcTemp.update(sql,ar);
}
//Client COde
public class Lab24Client {
public static void main(String[] args) {
ApplicationContext ctc=new ClassPathXmlApplicationContext("applicationContext.xml");
CustomerService c=(CustomerService)ctc.getBean("cs");
//add Customer
CustomerTO cust=new CustomerTO(102,"vsa","vsa#gmail.com",6154,"Pune");
c.addCustomer(cust);
}
//CustomerDAO
public interface CustomerDAO {
public void addCustomer(CustomerTO cto);
}
//spring ApplicationContext.xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="dataSource class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/vik"/>
<property name="username" value="root"/>
</bean>
<bean id="jdbcTemp" class="org.springframework.jdbc.core.JdbcTemplate" autowire="constructor"/>
<bean id="cdao" class="com.jlc.JdbcCustomerDAO"/>
<bean id="cs" class="com.jlc.CustomerServiceImpl"/>
//CustomerRowMapper
public class CustomerRowMapper implements RowMapper<CustomerTO>{
#Override
public CustomerTO mapRow(ResultSet rs, int rn) throws SQLException {
CustomerTO cto=new CustomerTO();
cto.setCid(rs.getInt(1));
cto.setCname(rs.getString(2));
cto.setEmail(rs.getString(3));
cto.setPhone(rs.getLong(4));
cto.setCity(rs.getString(5));
return cto;
}
}
//when I am running the client i got following excpetion
Exception in thread "main" java.lang.NullPointerException
at com.spring.CustomerServiceImpl.addCustomer(CustomerServiceImpl.java:11)
at com.spring.Lab24Client.main(Lab24Client.java:12)
//Please tell me what mistake i did with code or what's the problem in following program
You have to enable/register annotation config like below code in your xml.
<context:annotation-config/>

Categories