# 設置 Hibernate/JPA

(2) IntelliJ IDEA. Working with Hibernate/JPA - YouTube
以上的 link step by step 教你怎麼設置。 下面的會展示手動添加 Data Source 和 Properties 來連接 MySQL 的代碼。

  1. 在主要的 class 裡添加(純 Java main method 的 class)
private DataSource getDataSource() {
        final DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/courses");
        dataSource.setUsername("your-username");
        dataSource.setPassword("your-password");
        return dataSource;
    }
  1. 加入 properties
private Properties getProperties() {
        final Properties properties = new Properties();
        properties.put( "hibernate.dialect", "org.hibernate.dialect.MySQLDialect" );
        properties.put( "hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver" );
//        properties.put("hibernate.show_sql", "true");
        return properties;
  1. 新增 EntityManagerFactory 方法
private EntityManagerFactory entityManagerFactory(DataSource dataSource, Properties hibernateProperties ){
        final LocalContainerEntityManagerFactoryBean lemfb = new LocalContainerEntityManagerFactoryBean();
        lemfb.setDataSource(dataSource);
        lemfb.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        lemfb.setJpaProperties( hibernateProperties);
        lemfb.setPackagesToScan("com.tiffanyiong.demo.entity");
        lemfb.setPersistenceUnitName( "demo-unit" );
        lemfb.setPersistenceProviderClass(HibernatePersistenceProvider.class);
        lemfb.afterPropertiesSet();
        return lemfb.getObject();
    }