Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8207405
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T08:59:05+00:00 2026-06-07T08:59:05+00:00

City class is mapped to database. @Entity @Table(name = City) public class City implements

  • 0

City class is mapped to database.

@Entity
@Table(name = "City")
public class City implements Serializable, IRelationsQualifier
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    //-------------------------------------------------------
    @JsonIgnore
    @NotFound(action = NotFoundAction.IGNORE)
    @ManyToMany(
            fetch = FetchType.LAZY,
            cascade = {CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH},
            targetEntity = Event.class
        )
        @JoinTable(
               name="CityEvent",
               joinColumns = @JoinColumn( name="city_id"),
               inverseJoinColumns = @JoinColumn( name="event_id")
        )
    private Set<Event> eventList = new HashSet<Event>();

    public int getId()
    {
    return id;
    }
    public void setId(int id)
    {
    this.id = id;
    }

    @JsonIgnore
    public Set<Event> getEvents()
    {
    return eventList;
    }
    @JsonIgnore
    public void setEvents(Set<Event> events)
    {
    this.eventList = events;
    }


}

Dao layer for City.

package com.globerry.project.dao;
// removing imports to  make it easier to read   

@Repository
public class CityDao implements ICityDao
{

    @Autowired
    SessionFactory sessionFactory;
    @Autowired

    @Override
    public City getCityById(int id)
    {
    City city = (City) sessionFactory.getCurrentSession().load(City.class, id);
    return city;
    }
}

Test:

package com.globerry.project.dao;
// removing time imports to make it easier to read.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/META-INF/spring/daoTestContext.xml")
@TestExecutionListeners({
    DependencyInjectionTestExecutionListener.class,
    DirtiesContextTestExecutionListener.class, ContextLoaderListener.class
})
public class CityDaoTest {

    @Test
    @Transactional(readOnly=false)
    public void LazyTest()
    {
        City city1 = new City();
        city1.setName("Bobryjsk1");
        try
        {
        cityDao.addCity(city1);
        }
        catch (MySqlException e) 
        {
        e.printStackTrace(System.err);
        }
        Event ev = new Event();
        ev.setName("Disnayland");
        eventDao.addEvent(ev, city1);
        ev = new Event();
        ev.setName("Disnayland5");
        eventDao.addEvent(ev, city1);
        System.err.println("1");
        city1 = cityDao.getCityById(city1.getId());//there i saw in debug that events have been already inizialized 
        System.err.println("2");
        System.err.println(Hibernate.isInitialized(city1.getEvents()));//returns true
        Iterator<Event> it = city1.getEvents().iterator();
        System.err.println("3");
        ev = it.next();
        System.err.println(ev.getName());
        ev = new Event();
        ev.setName("Disnayland55");
        eventDao.addEvent(ev, city1);
    }

}

root-context:

<?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:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">


    <!-- <jdbc:embedded-database id="dataSource" type="H2"/> -->
    <context:annotation-config />
    <context:component-scan base-package="com.globerry.project.domain" />
    <context:component-scan base-package="com.globerry.project.dao" /> 
    <context:component-scan base-package="com.globerry.project.service" />


        <!-- Файл с настройками ресурсов для работы с данными (Data Access Resources) -->
        <tx:annotation-driven transaction-manager="transactionManager" /> 
    <!-- Менеджер транзакций -->


    <!-- Настройки бина dataSource будем хранить в отдельном файле -->
  <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="classpath:/META-INF/jdbc.properties" />

    <!-- Непосредственно бин dataSource -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        p:driverClassName="com.mysql.jdbc.Driver" 
        p:url="${jdbc.databaseurl}"
        p:username="${jdbc.username}" 
        p:password="${jdbc.password}" />

    <!-- Настройки фабрики сессий Хибернейта -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
        p:packagesToScan="com.globerry.project.Dao">

        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop> 
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
                <prop key="hibernate.connection.charSet">UTF-8</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
          p:sessionFactory-ref="sessionFactory">
        <qualifier value="transactionManager"/>
    </bean>
</beans>

When I’m using method ‘getCityById()’ in my ‘LazyTest()’ in debug mode I get strange result. In debug i see that my event collection was initialized, before I use it for the first time. But I’m using Lazy Fetch Strategy. What is wrong?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T08:59:06+00:00Added an answer on June 7, 2026 at 8:59 am

    That is because it is already in the session. Load returns the City object that you just created – not fetching it from the database.

    Add the following code before the getCityById call – you will get the result you are expecting.

    sessionFactory.getCurrentSession().flush()
    sessionFactory.getCurrentSession().clear()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

What am i missing? City.cs [Table(Name = City)] public class City { [Column(IsDbGenerated =
Consider following code public class City { public string Name { get { return
I have the following models: class City(models.Model): name = models.CharField(max_length=100) class Pizza(models.Model): name =
public class User { public long Id {get;set;} [References(typeof(City))] public long CityId {get;set;} [????]
I have a Person class mapped to a PERSON table, and an Address class
So I have a few Django models that look like this: class City(models.Model): name
In my NHIbernate (Database Model) I have this : public class Pers { public
I have a City class and inside that a Detail class: public class City
I have two models for store and city: class City(models.Model): name = models.CharField() slug
Consider these 3 models: # models.py class City(models.Model): name = models.CharField(max_length=50) class Institute(models.Model): name

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.