Junior — Middle
What approach is better for adding data to a repository?
sobes.tech AI
Answer from AI
To add data to a repository in Java, the Repository pattern is commonly used, which encapsulates data access logic. It is better to use repository methods that accept an entity object and save it via ORM (such as JPA/Hibernate) or directly through JDBC.
Example using Spring Data JPA:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// getters and setters
}
public interface UserRepository extends JpaRepository<User, Long> {}
// In the service
@Autowired
private UserRepository userRepository;
public void addUser(User user) {
userRepository.save(user); // adds or updates the entity
}
This approach provides convenience, security, and abstracts the details of database operations.